我很难弄清楚如何在python string中扭转几个单词。
ex:
aString = "This is my string."
我知道如何扭转整个字符串,但是我不知道如何仅逆转几个单词,例如:
我需要以偶数索引,2、4、6、8、10、12
扭转每个单词aString = "This si my gnirts"
您可以使用 enumerate
在用 str.split
分开后与项目旁边生成索引,并在 odd 上反转这些索引(即使不计数从零开始(。使用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'
您可以做到这一点:
newString = []
for index, i in enumerate(aString.split()):
if i % 2 == 0:
newString.append(i[::-1])
else:
newString.append(i)
newString = ''.join(newString)
如果要在一行中进行...
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'
注意:我知道您说您正在寻找原始问题中的索引,但是看起来您实际上是根据示例寻找奇怪的索引。只需将mod切换为%2 == 0如果我错了。