Python 使用户输入的字母从字符串中消失

Python 使用户输入的字母从字符串中消失,python,for-loop,replace,Python,For Loop,Replace,谁能帮我做点简单的事,但我似乎遇到了一个小麻烦 我需要从用户那里获取一个随机字符串的输入。然后我需要询问用户希望我从字符串中删除哪些字母 然后,我需要使用for循环使那些特定的字母从字符串中消失,并打印显示丢失的字母 我的代码如下: user_input = input("Please enter a string") disappear = input("now please enter the chracters you would like to disappear") for a in

谁能帮我做点简单的事,但我似乎遇到了一个小麻烦

我需要从用户那里获取一个随机字符串的输入。然后我需要询问用户希望我从字符串中删除哪些字母

然后,我需要使用for循环使那些特定的字母从字符串中消失,并打印显示丢失的字母

我的代码如下:

user_input = input("Please enter a string")
disappear = input("now please enter the chracters you would like to disappear")
for a in user_input.replace(disappear, " "):
    print (a)
我的代码运行,但打印出每一个新的行上的字母,并使我选择的字母消失,但它也使其他字母消失

任何最简单的帮助都将不胜感激。
谢谢

您可以通过替换每个字母来完成此操作:

user_input = input("Please enter a string")
disappear = input("now please enter the chracters you would like to disappear")
for a in disappear :
    user_input = user_input.replace(a, '')
print(user_input)
您的原始脚本无法工作的原因是因为以下这部分:

for a in user_input.replace(disappear, " "):
    print (a)
到底发生了什么?首先,你要评估:

user_input.replace(disappear, " ")
假设我的
user\u输入是'hello world',
dissapear
是'he'。这将被评价为“世界”。现在发生了什么:

for a in 'llo world':
    print(a)
您可以看到它应该打印:

l
l
o

w
o
r
l
d

要在Python中的同一行上打印,请传递kwarg“end=''”:

print(a, end='')
我在这段代码中看到的另一个问题是,您正在替换消失子字符串的实例,而不是消失中的单个字母。根据对程序预期用途的描述,听起来您希望替换用户键入的所有字母