我想将一个字符串拆分为两个集合,例如,将一个字符串拆分为两个集合
['abcdefg']
到
['ab','cd','ef']
这是我到目前为止有:
string = 'acabadcaa\ndarabr'
newString = []
for i in string:
newString.append(string[i:i+2])
我想将一个字符串拆分为两个集合,例如,将一个字符串拆分为两个集合
['abcdefg']
到
['ab','cd','ef']
这是我到目前为止有:
string = 'acabadcaa\ndarabr'
newString = []
for i in string:
newString.append(string[i:i+2])
def splitCount(s, count):
return [''.join(x) for x in zip(*[list(s[z::count]) for z in range(count)])]
splitCount('abcdefg',2)
这是一个问题的答案,但如果OP不知道如何分片我不认为他会理解'zip','join'或列表理解,一个解释将是很好的在这种情况下。 – 2014-10-02 11:19:05
一种选择使用正则表达式:
>>> import re
>>> re.findall(r'..', 'abcdefg')
['ab', 'cd', 'ef']
re.findall
返回一个字符串中所有不重叠匹配的列表。 '..'
表示匹配任何两个连续字符。
为字符串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']
我没有downvote,但是这输出'['ab','cd','ef','g']'这不是OP指定的。 – 2014-10-02 11:28:34
@ajcr:thx为你抬头。纠正了我的版本。 – 2014-10-02 11:36:28
这个函数会得到任何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']
试试这个
s = "abcdefg"
newList = [s[i:i+2] for i in range(0,len(s)-1,2)]
你有试过什么吗? – 2014-10-02 11:13:56
我使用一个for循环中作为这样的思维切片:字符串= 'acabadcaa \ ndarabr' newString = [] 对于i在字符串: newString.append(字符串[I:+ 2]) – 2014-10-02 11:16:23
这很好尝试分片,如果你有问题或异常发布,所以我们可以提供帮助。 – 2014-10-02 11:17:16