如何在python 3中使用.replace()反转字符串?

问题描述 投票:0回答:1

我的代码假定将str1中的每个字符替换为str2中的字符,因此最后str1和str2具有相同的值。有人可以解释为什么这不起作用吗?它可以一直工作到x = 2为止,从x = 3一直到最后,代码都变得疯狂了,只需添加废话即可。

str1, str2= "Donkey", "Yeknod"

for x in range(len(str1)): 
    str1=str1.replace(str1[x], str2[x])
python-3.x string replace reverse
1个回答
0
投票

这是您的前三个替代品,它们按您的预期工作:

replace('D', 'Y') --> Yonkey
replace('o', 'e') --> Yenkey
replace('n', 'k') --> Yekkey

此后,您开始替换在str1中多次出现的字符。

replace('k', 'n') --> Yenney
replace('e', 'o') --> Yonnoy
replace('y', 'd') --> Yonnod

replace不是用于反转字符串的合适方法,因为它会替换所有匹配的字符,而不仅仅是您要替换的字符。

© www.soinside.com 2019 - 2024. All rights reserved.