Basically I have a dictionary with 10 elements and I'm replacing user input string with those stored in the dictionary like so
基本上我有一个包含10个元素的字典,我正在用这样存储在字典中的字符串替换用户输入字符串
abc_dict { 'a':'Apple','b':'Banana','c':'Cat'}:
str = user input
for key, value in abc_dict.iteritems():
str = str.replace(key, value)
print str
However when I print this it prints a line for each element in the dictionary and only the last line is fully replaced. Example of my output
但是当我打印它时,它会为字典中的每个元素打印一行,并且只完全替换最后一行。我的输出示例
I like a, b, and c
I like apple, banana, and c
I like apple, banana, and cat
What concept must I use in order for it to only print the last line
我必须使用什么概念才能打印最后一行
1 个解决方案
#1
0
Right code:
abc_dict { 'a':'Apple','b':'Banana','c':'Cat'}:
str = user input
for key, value in abc_dict.iteritems():
str = str.replace(key, value)
print str
Your error: you use print str
inside the for
loop
您的错误:您在for循环中使用print str
#1
0
Right code:
abc_dict { 'a':'Apple','b':'Banana','c':'Cat'}:
str = user input
for key, value in abc_dict.iteritems():
str = str.replace(key, value)
print str
Your error: you use print str
inside the for
loop
您的错误:您在for循环中使用print str