import re , strings , os ,sys
sentence = "abcdefghijkl"
for i in range(0,len(sentence),3):
twoletters = sentence[i:i+2] + sentence[i+1:i+3]
print twoletters
这给了我:
abbc
deef
ghhi
jkkl
我想要的地方:
ab
bc
cd
de
ef
fg
gh
hi
ij
jk
kl
如何进行此类拼接?
答案 0 :(得分:3)
>>> sentence = "abcdefghijkl"
>>> [sentence[i:i+2] for i in range(len(sentence) - 1)]
['ab', 'bc', 'cd', 'de', 'ef', 'fg', 'gh', 'hi', 'ij', 'jk', 'kl']
答案 1 :(得分:1)
与你的想法保持一致但是简化,我会做以下
for i in range(0, len(sentence)-1):
print sentence[i] + sentence[i + 1]
答案 2 :(得分:1)
>>>sentence = "abcdefghijkl"
>>>for i in range(0, len(sentence)-1):
>>> print sentence[i:i+2]
ab
bc
cd
de
ef
fg
gh
hi
ij
jk
kl
>>>[sentence[i:i+2] for i in range(0, len(sentence)-1)]
['ab', 'bc', 'cd', 'de', 'ef', 'fg', 'gh', 'hi', 'ij', 'jk', 'kl']
答案 3 :(得分:0)
>>> from itertools import tee, izip, islice
>>> sentence = "abcdefghijkl"
>>> x, y = tee(sentence)
>>> y = islice(y, 1, None)
>>> for a,b in izip(x, y):
... print a + "" + b
答案 4 :(得分:0)
[sentence[i:i+2] for i in range(0,len(sentence)-1,1)]
['ab','bc','cd','de','ef','fg','gh','hi','ij','jk','kl']