wro*_*ame 3 python user-input newline input
我在Python中有这个代码
inputted = input("Enter in something: ")
print("Input is {0}, including the return".format(inputted))
Run Code Online (Sandbox Code Playgroud)
那个输出
Enter in something: something
Input is something
, including the return
Run Code Online (Sandbox Code Playgroud)
我不确定发生了什么; 如果我使用不依赖于用户输入的变量,我在使用变量格式化后不会获得换行符.我怀疑当我点击返回时,Python可能会将换行符作为输入.
我怎样才能使输入不包含任何换行符,以便我可以将它与其他字符串/字符进行比较?(例如something == 'a')
你是对的 - 包含换行符inputted.要删除它,您只需调用strip("\r\n")从结尾删除换行符:
print("Input is {0}, including the return".format(inputted.strip("\r\n")))
Run Code Online (Sandbox Code Playgroud)
如果最后inputted没有换行符,这不会导致任何问题,但会删除那里的任何换行符,因此您可以使用它,无论是否inputted是用户输入.
如果您根本不想在文本中添加任何换行符,则可以使用inputted.replace("\r\n", "")删除所有换行符.