python - 如何在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)
解决方案
正如人们在评论中所说,字符串是不可变的。这意味着您实际上无法更改现有字符串的值 - 但您可以创建一个包含您想要进行的更改的新字符串。
在您的情况下,您正在使用该.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')):
...
推荐阅读
- javascript - 导入函数说“x 不是函数”,但在控制台日志返回函数。网页包
- scala - 通过 Eithers 对共享错误状态进行建模以用于显式错误声明
- excel - 将多张工作表导出为一个csv文件excel vba
- delphi - DataSnap WebBroker 应用程序,“尚未调用 Coinitialize”
- javascript - 如何从 Typescript 中的对象内联解构嵌套的可选属性?
- tsql - 如何查看一个表是否为空?
- flutter - 如何每隔 x 秒更新一次来自手机状态的文本数据
- spring - 为什么 Spring Boot 应用启动时会出现异常?
- airflow - 如何使用气流声明复杂的依赖关系
- reactjs - 在 nextjs 中实现实时网络通知推送器