2012-11-09 232 views

回答

7
>>> s = 'akhfkahgdsds' 
>>> range(0, len(s), 2) # gives you the start indexes of your substrings 
[0, 2, 4, 6, 8, 10] 
>>> [s[i:i+2] for i in range(0, len(s), 2)] # gives you the substrings 
['ak', 'hf', 'ka', 'hg', 'ds', 'ds'] 
>>> ' '.join(s[i:i+2] for i in range(0, len(s), 2)) # join the substrings with spaces between them 
'ak hf ka hg ds ds' 
+0

其實,這個命令不起作用,我正在使用python 2.7.3 – Leo

+0

@ user1813163我已經在Python 2.7和3.3上測試了它。你確定你粘貼正確嗎?你遇到了什麼錯誤? –

0
def isection(itr, size): 
    while itr: 
     yield itr[:size] 
     itr = itr[size:] 

' '.join(isection('akhfkahgdsds', 2)) 
0

我真的不認爲這是去這裏的路,但我覺得這個答案是一種樂趣呢。如果字符串的長度總是甚至,你可以用iter起到巧妙的技巧 - 如果是奇數,則最後一個字符將被截斷:

s = '11223344' 
i_s = iter(s) 
' '.join(x+next(i_s) for x in i_s) 

當然,你可以隨時填充它:

i_s = iter(s+len(s)%2*' ') 
+0

非常感謝,它幫助了我) – Leo

0

你可以試試這個簡單的代碼:

try: 
    for i in range(0,len(s)+1,2): 
     print s[i]+s[i+1], 
except IndexError: 
    pass