首页 > 解决方案 > 如何在Python中删除输入中的空格

问题描述

我正在编写一个程序,要求用户输入他的名字。

如果名称以a,b或开头c,则程序应打印("Your name starts with a, b or c")

不幸的是,如果用户首先输入一个空格,然后输入他的名字,程序会认为名字以空格开头,"Your name doesn't start with a, b or c"即使名字以这些字母开头,它也会自动打印。

我现在想删除输入中的空格,这样这个问题就不会再发生了。

到目前为止,我已经尝试过if name.startswith((" ")): name.replace(" ", "") 感谢您的帮助!

name = input("Hi, who are you?")
if name.startswith((" ")):
    name.replace(" ", "")

if name.startswith(('a', 'b', 'c')):
    print("Your name starts with a, b or c")
    print(name)
else:
    print("Your name doesn't start with a, b or c")
    print(name)

标签: pythoninputspacestartswith

解决方案


正如人们在评论中所说,字符串是不可变的。这意味着您实际上无法更改现有字符串的值 - 但您可以创建一个包含您想要进行的更改的新字符串。

在您的情况下,您正在使用该.replace()函数- 此函数在替换发生后返回一个新字符串。一个简单的例子:

str = 'I am a string'
new_string = str.replace('string', 'boat')

请注意,变量new_string现在包含所需的更改 - “我是一艘船”,但原始str变量保持不变。

要直接回答您的问题,您需要使用修剪空白后创建的变量。您甚至可以重复使用相同的变量:

if name.startswith((" ")):
    name = name.replace(" ", "") # override "name" with the new value

if name.startswith(('a', 'b', 'c')):
    ...

推荐阅读