-1
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

这种拼接怎么做?

4

5 回答 5

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']
于 2012-06-19T14:23:28.873 回答
1

与您的想法保持一致但简化,我将执行以下操作

for i in range(0, len(sentence)-1):
    print sentence[i] + sentence[i + 1]
于 2012-06-19T14:28:50.083 回答
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']
于 2012-06-19T14:29:02.363 回答
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']

于 2012-06-20T06:04:50.703 回答
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
于 2012-06-19T15:29:34.820 回答