我想在python中删除字符串中的字符:
string.replace(',', '').replace("!", '').replace(":", '').replace(";", '')...
但我有很多字符必须删除。我想了一个清单
list = [',', '!', '.', ';'...]
但是如何使用列表来替换字符串中的字符呢?
我想在python中删除字符串中的字符:
string.replace(',', '').replace("!", '').replace(":", '').replace(";", '')...
但我有很多字符必须删除。我想了一个清单
list = [',', '!', '.', ';'...]
但是如何使用列表来替换字符串中的字符呢?
当前回答
你可以使用str.translate():
s.translate(None, ",!.;")
例子:
>>> s = "asjo,fdjk;djaso,oio!kod.kjods;dkps"
>>> s.translate(None, ",!.;")
'asjofdjkdjasooiokodkjodsdkps'
其他回答
你可以使用str.translate():
s.translate(None, ",!.;")
例子:
>>> s = "asjo,fdjk;djaso,oio!kod.kjods;dkps"
>>> s.translate(None, ",!.;")
'asjofdjkdjasooiokodkjodsdkps'
你可以用这样的东西
def replace_all(text, dic):
for i, j in dic.iteritems():
text = text.replace(i, j)
return text
这不是我自己的代码,来自这里,这是一篇伟大的文章,并深入讨论了这样做
Python 3,单行列表综合实现。
from string import ascii_lowercase # 'abcdefghijklmnopqrstuvwxyz'
def remove_chars(input_string, removable):
return ''.join([_ for _ in input_string if _ not in removable])
print(remove_chars(input_string="Stack Overflow", removable=ascii_lowercase))
>>> 'S O'
这个怎么样,一行字。
reduce(lambda x,y : x.replace(y,"") ,[',', '!', '.', ';'],";Test , , !Stri!ng ..")
我在想一个解决办法。首先,我将字符串输入作为一个列表。然后我将替换列表中的项。然后通过join命令,我将返回list作为字符串。代码可以是这样的:
def the_replacer(text):
test = []
for m in range(len(text)):
test.append(text[m])
if test[m]==','\
or test[m]=='!'\
or test[m]=='.'\
or test[m]=='\''\
or test[m]==';':
#....
test[n]=''
return ''.join(test)
这将删除字符串中的任何内容。你怎么看?