2017-04-24 186 views
0

我很難找出如何在python字符串中顛倒幾個字。顛倒python字符串中的字符

例如:

aString = "This is my string." 

我知道如何扭轉整個字符串,但我無法弄清楚如何扭轉只有幾句話,如:我需要扭轉的每一個字

偶數索引,2,4,6,8,10,12

aString = "This si my gnirts" 

回答

4

可以使用enumerate以產生沿着分割後的項目索引與str.split和扭轉這些在奇數(甚至從零開始計數)指數。使用str.join重建字符串:

>>> s = "This is my string" 
>>> ' '.join(x if i%2==0 else x[::-1] for i, x in enumerate(s.split())) 
'This si my gnirts' 
+0

這工作完美,非常感謝你! –

+0

@ZackWalton如果有幫助,你可以接受 –

1

你可以這樣做:

newString = [] 
for index, i in enumerate(aString.split()): 
    if i % 2 == 0: 
     newString.append(i[::-1]) 
    else: 
     newString.append(i) 
newString = ''.join(newString) 
0

如果你想這樣做在同一行...

out = ' '.join([x[::-1] if input.index(x)%2 == 1 else x for x in input.split(' ')]) 

例:

>>> input = 'here is an example test string' 
>>> out = ' '.join([x[::-1] if input.index(x)%2 == 1 else x for x in input.split(' ')]) 
>>> out 
'here si an elpmaxe tset string' 

注:我知道你說過你希望在你的原始問題中反轉甚至是索引,但是看起來你實際上是在根據你的例子尋找奇怪的索引。只要將模式切換到%2 == 0,如果我錯了。