"我正在尝试使用 str.lsplit(( 功能从字符串中删除user_input尾随空格">
我已经尝试了两种情况的str.lsplit((
case1:将输入消息作为字符串从用户>未按预期获得结果
case2:将输入消息硬编码为字符串>按预期获得结果
我的代码
'''string1 = str(input("Enter your message non case sensitive"))
string2 = " This is Test String2 to strip leading space"
print ("str.lsplit() functionality is NOT WORKING as expected for
user inputn","user_Input String1n",string1,"nuser_output
String2n",string1.lstrip())
print ("str.lsplit() functionality is WORKING for hardcoded string
inputn","Input String2n",string2,"noutput
String2n",string2.lstrip())
'''
实际结果
'''Enter your message non case sensitive " This is Test String1 to
strip leading space"
str.lsplit() functionality is NOT WORKING as expected for user
input
user_Input String1
" This is Test String1 to strip leading space"
user_output String2
" This is Test String1 to strip leading space"
str.lsplit() functionality is WORKING for hardcoded string input
Input String2
This is Test String2 to strip leading space
output String2
This is Test String2 to strip leading space
Process finished with exit code 0
'''
预期成果
期望通过从user_input方案中删除尾随空格来获取输出
目前还不清楚您遇到了什么问题。你提到lsplit
,这甚至不是一个函数。 split
是一个函数,但我相信你的意思是lstrip
.你的代码非常混乱。尝试这样的事情,改为:
string1 = input("Enter your message non case sensitive: ") # Input always returns a str in Python 3
string2 = " This is Test String2 to strip leading space"
print(f"string1 = '{string1}'")
print(f"string2 = '{string2}'")
print(f"string1 left stripped = '{string1.lstrip()}'")
print(f"string2 left stripped = '{string2.lstrip()}'")
这是我输入" ASD "
时的输出:
Enter your message non case sensitive: ASD
string1 = ' ASD '
string2 = ' This is Test String2 to strip leading space'
string1 left stripped = 'ASD '
string2 left stripped = 'This is Test String2 to strip leading space'
lstrip
删除前导空格,而不是尾随空格。为此使用 rstrip
,或strip
删除两者。另请注意,在 Python 中字符串是不可变的,因此这些函数不会更改字符串本身,而是返回一个全新的字符串,然后您可以将其分配给变量,如下所示:
string2 = " This is Test String2 to strip leading space"
string2 = string2.lstrip()