在python中拆分字符串后删除空格

时间:2016-10-29 23:11:26

标签: string parsing indexing removing-whitespace

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.

我用这些说明写了一个程序,虽然我无法弄清楚如何删除可能附加到输出单词的额外空格。例如,如果您输入“Billy,Bob”,它可以正常工作,但如果您输入“Billy,Bob”,您将获得IndexError:列表索引超出范围,或者如果您输入“Billy,Bob”,Billy将输出附加到字符串的额外空间。这是我的代码。

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(“,”)?

1 个答案:

答案 0 :(得分:0)

您可以使用.trim()方法删除前导和尾随空格。 usrIn.trim().split(",")。完成此操作后,您可以使用空白正则表达式再次拆分它们,例如usrIn.split("\\s+") \s将查找空格,而+运算符将查找重复的空格。

希望这会有所帮助:)