为什么python会在字典中添加字母?

为什么python会在字典中添加字母?,python,Python,我最近一直在尝试用python编写一个程序来制作文本密码,但实际情况如下: text='abab'#the text we want to replace result=''#we are going to replace it replace_map={'a':'b', # a dictionary map to replace the text 'b':'a' } for ch in text: #loop through every text in the loop i

我最近一直在尝试用python编写一个程序来制作文本密码,但实际情况如下:

text='abab'#the text we want to replace
result=''#we are going to replace it
replace_map={'a':'b', # a dictionary map to replace the text
   'b':'a'


}

for ch in text: #loop through every text in the loop
    if ch  in replace_map: # if the text is in the replace map 
        result += replace_map[ch] #then we are going to replace every letter in it from replace map

else:
    result += ch#else just add the value with no changing

print(text)#for comparison
print(result)#then print the text after replacing it


我希望结果文本是'abab'而不是'babab'。
请提供帮助。

问题是您的else语句超出for循环,只需向它添加一个缩进,它就会给出您的结果。

Python中的缩进非常关键!解释器误解了程序的流程,因为
else
关键字没有正确缩进。尝试使用IDE,IDE通常能够根据需要缩进代码(
if
else
语句位于同一级别,等等)

如果正确缩进代码,它将如下所示。我已经在我的机器上测试了这个代码,我可以确认它可以工作

text='abab'#我们要替换的文本
结果=“”#我们将替换它
替换映射={
'a':'b',#替换文本的字典映射
“b”:“a”
}
对于ch-in-text:#循环遍历循环中的每个文本
如果替换映射中有ch:#如果文本在替换映射中
result+=replace_-map[ch]#然后我们将替换replace-map中的每个字母
其他:
result+=ch#否则只需添加值而不进行更改
打印(文本)#用于比较
打印(结果)#替换后打印文本

缩进严重的python代码是无效的python代码。
else:result+=ch
块的行为取决于它的缩进:它现在的方式——没有缩进——使它成为……else的
的一部分。您确定要这个而不是
if…else
?如果代码缩进与文本编辑器中的缩进不匹配,请回答您的问题。看起来缩进不正确。你的意思是缩进
else:
成为
if
的一部分,而不是成为
for
的一部分吗