2014-10-02 171 views
-3

我想將一個字符串拆分爲兩個集合,例如,將一個字符串拆分爲兩個集合

['abcdefg'] 

['ab','cd','ef'] 

這是我到目前爲止有:

string = 'acabadcaa\ndarabr' 
newString = [] 

for i in string: 
    newString.append(string[i:i+2]) 
+1

你有試過什麼嗎? – 2014-10-02 11:13:56

+0

我使用一個for循環中作爲這樣的思維切片:字符串= 'acabadcaa \ ndarabr' newString = [] 對於i在字符串: newString.append(字符串[I:+ 2]) – 2014-10-02 11:16:23

+0

這很好嘗試分片,如果你有問題或異常發佈,所以我們可以提供幫助。 – 2014-10-02 11:17:16

回答

1
def splitCount(s, count): 
    return [''.join(x) for x in zip(*[list(s[z::count]) for z in range(count)])] 

splitCount('abcdefg',2) 
+0

這是一個問題的答案,但如果OP不知道如何分片我不認爲他會理解'zip','join'或列表理解,一個解釋將是很好的在這種情況下。 – 2014-10-02 11:19:05

2

一種選擇使用正則表達式:

>>> import re 
>>> re.findall(r'..', 'abcdefg') 
['ab', 'cd', 'ef'] 

re.findall返回一個字符串中所有不重疊匹配的列表。 '..'表示匹配任何兩個連續字符。

0

爲字符串s分成的(保證)等長的長度爲n的子串,和截斷更小的片段的列表:

n = 2 
s = 'abcdef' 
lst = [s[i:i+n] for i in xrange(0, len(s)-len(s)%n, n)] 

['ab', 'cd', 'ef'] 
+0

我沒有downvote,但是這輸出'['ab','cd','ef','g']'這不是OP指定的。 – 2014-10-02 11:28:34

+0

@ajcr:thx爲你擡頭。糾正了我的版本。 – 2014-10-02 11:36:28

0

這個函數會得到任何chunk

def chunk(s,chk): 
    ln = len(s) 
    return [s[i:i+chk] for i in xrange(0, ln - ln % chk, chk)] 

In [2]: s = "abcdefg" 

In [3]: chunk(s,2) 
Out[3]: ['ab', 'cd', 'ef'] 

In [4]: chunk(s,3) 
Out[4]: ['abc', 'def'] 

In [5]: chunk(s,5) 
Out[5]: ['abcde'] 
0

試試這個

s = "abcdefg" 
newList = [s[i:i+2] for i in range(0,len(s)-1,2)] 
相關問題