Python中输入的space如何删除

How to delete space in the input in Python

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

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

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

我现在想删除输入中的space,这样这个问题就不会再出现了。

到目前为止我已经试过了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)

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

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

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

请注意,变量 new_string 现在包含所需的更改 - "I am a boat" 但原始 str 变量保持不变。

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

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

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

字符串是不可变的,replace 不会修改调用它的字符串,而是 returns 一个您可以直接在代码中冷使用的新字符串:

name = input("Hi, who are you?")

if name.replace(" ", "").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")

您也可以创建一个新变量或重新分配 name:

name = name.replace(" ", "")

以防您要在代码中进一步使用它。

字符串是不可变的。对字符串的任何操作都不会改变这个字符串

name.replace(" ", "") 不修改 name 但 return 一个新字符串并让 name 不变

所以你可以写

new_name = name.replace(" ", "")

不过你也可以这样写

name = name.replace(" ", "")

在这种情况下,原始字符串没有被修改。但是它的名字被重用来接收 name.replace(" ", "")

的结果

哪种写法最好取决于你问谁。我更喜欢第二个

# get name as user input and clean    
name = input("Hi, what is your name? ").lower().strip()

# conditional based on intial letter of name
print("Your name starts with a,b or c" if name.startswith(("a", "b", "c")) else "Your name doesn't start with a,b or c")

print(name.capitalize())