0
1)Prompt the user for a string that contains two strings separated by a comma.
2)Report an error if the input string does not contain a comma. Continue to prompt until a valid string is entered. Note: If the input contains a comma, then assume that the input also contains two strings.
3)Using string splitting, extract the two words from the input string and then remove any spaces. Output the two words.
4)Using a loop, extend the program to handle multiple lines of input. Continue until the user enters q to quit.
我用這些指令編寫了一個程序,但我無法計算出如何去除可能附加到輸出字上的多餘空格。例如,如果你輸入「比利,鮑勃」它工作正常,但如果你輸入「比利,鮑勃」,你會得到一個IndexError:列表索引超出範圍,或者如果你輸入「比利,鮑勃」比利將輸出一個額外的空間附加到字符串。這是我的代碼。在python中拆分字符串後刪除空格
usrIn=0
while usrIn!='q':
usrIn = input("Enter input string: \n")
if "," in usrIn:
tokens = usrIn.split(", ")
print("First word:",tokens[0])
print("Second word:",tokens[1])
print('')
print('')
else:
print("Error: No comma in string.")
如何從輸出中刪除空格,以便我可以使用usrIn.split(「,」)?