我不断获取用户输入的字符串,然后尝试删除任何非字符或数字的字符。
我开发的方法涉及按空格拆分字符串,然后分析每个单词以查找无效字符。
我很难将单词重新组合在一起,每个单词之间都有空格。我试过使用 ' '.join(list) 但它会在每个字符或数字之间放置一个空格。
请您参考如下方法:
当然,@Ashwini 的答案比这更好,但是如果你仍然想只用循环来做
strings = raw_input("type something")
while(True):
MyString = ""
if strings == "stop": break
for string in strings.split():
for char in string:
if(char.isalnum()): MyString += char
MyString += " "
print MyString
strings = raw_input("continue : ")
样本运行
$ python Test.py
type somethingWelcome to$%^ Python
Welcome to Python
continue : I love numbers 1234 but not !@#$
I love numbers 1234 but not
continue : stop
编辑
Python 3 版本:
正如 Ashwini 在评论中指出的那样,将字符存储在列表中并在末尾打印带有连接的列表。
strings = input("type something : ")
while(True):
MyString = []
if strings == "stop": break
for string in strings.split():
for char in string:
if(char.isalnum()): MyString.append(char)
MyString.append(" ")
print (''.join(MyString))
strings = input("continue : ")
样本运行:
$ python3 Test.py
type something : abcd
abcd
continue : I love Python 123
I love Python 123
continue : I hate !@#
I hate
continue : stop
