2012-06-19 31 views
-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 

如何做這樣的拼接?

回答

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

保持符合你的思維,但簡化,我會做以下

for i in range(0, len(sentence)-1): 
    print sentence[i] + sentence[i + 1] 
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 

或者使用List Comprehension

>>>[sentence[i:i+2] for i in range(0, len(sentence)-1)] 
['ab', 'bc', 'cd', 'de', 'ef', 'fg', 'gh', 'hi', 'ij', 'jk', 'kl'] 
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 
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']