我正在连续输入用户输入的字符串,然后尝试删除任何不是字符或数字的字符。
我开发的方法包括用空格分割字符串,然后分析每个单词以找到无效字符。
我很难把单词放回去,每个单词之间都有空格。我尝试使用''.join(list),但它在每个字符或数字之间放置一个空格。
答案 0 :(得分:4)
当然,@ 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
答案 1 :(得分:2)
strs = "foo12 #$dsfs 8d"
ans = []
for c in strs:
if c.isalnum():
ans.append(c)
elif c.isspace(): #handles all types of white-space characters \n \t etc.
ans.append(c)
print ("".join(ans))
#foo12 dsfs 8d
使用str.translate
:
>>> from string import punctuation, whitespace
>>> "foo12 #$dsfs 8d".translate(None,punctuation)
'foo12 dsfs 8d'
要删除空格:
>>> "foo12 #$dsfs 8d".translate(None,punctuation+whitespace)
'foo12dsfs8d'
或regex
:
>>> import re
>>> strs = "foo12 #$dsfs 8d"
>>> re.sub(r'[^0-9a-zA-Z]','',strs)
'foo12dsfs8d'
使用str.join
,str.isalnum
和str.isspace
:
>>> strs = "foo12 #$dsfs 8d"
>>> "".join([c for c in strs if c.isalnum() or c.isspace()])
'foo12 dsfs 8d'
答案 2 :(得分:0)
这是我的解决方案。有关详细信息,请参阅评论:
def sanitize(word):
"""use this to clean words"""
return ''.join([x for x in word if x.isalpha()] )
n = input("type something")
#simpler way of detecting stop
while(n[-4:] != 'stop'):
n += " " + input("continue : ")
n = n.split()[:-1]
# if yuo use list= you are redefining the standard list object
my_list = [sanitize(word) for word in n]
print(my_list)
strn = ' '.join(my_list)
print(strn)
答案 3 :(得分:0)
您可以使用连接和列表推导来完成此操作。
def goodChars(s):
return " ".join(["".join([y for y in x if y.isdigit() or y.isalpha()]) for x in s.split()])