我想在python中删除字符串中的字符:
string.replace(',', '').replace("!", '').replace(":", '').replace(";", '')...
但我有很多字符必须删除。我想了一个清单
list = [',', '!', '.', ';'...]
但是如何使用列表来替换字符串中的字符呢?
我想在python中删除字符串中的字符:
string.replace(',', '').replace("!", '').replace(":", '').replace(";", '')...
但我有很多字符必须删除。我想了一个清单
list = [',', '!', '.', ';'...]
但是如何使用列表来替换字符串中的字符呢?
当前回答
另一种使用regex的方法:
''.join(re.split(r'[.;!?,]', s))
其他回答
您可以使用翻译方法。
s.translate(None, '!.;,')
如果您正在使用python3并寻找翻译解决方案-函数已更改,现在接受1个参数而不是2个参数。
该参数是一个表(可以是字典),其中每个键都是要查找的字符的Unicode序数(int),值是替换值(可以是要将键映射到的Unicode序数或字符串)。
下面是一个用法示例:
>>> list = [',', '!', '.', ';']
>>> s = "This is, my! str,ing."
>>> s.translate({ord(x): '' for x in list})
'This is my string'
你可以用这样的东西
def replace_all(text, dic):
for i, j in dic.iteritems():
text = text.replace(i, j)
return text
这不是我自己的代码,来自这里,这是一篇伟大的文章,并深入讨论了这样做
你可以使用str.translate():
s.translate(None, ",!.;")
例子:
>>> s = "asjo,fdjk;djaso,oio!kod.kjods;dkps"
>>> s.translate(None, ",!.;")
'asjofdjkdjasooiokodkjodsdkps'
另外一个有趣的话题是将UTF-8重音字符从字符串中移除,将其转换为标准的非重音字符:
在python unicode字符串中删除重音的最佳方法是什么?
从主题摘录的代码:
import unicodedata
def remove_accents(input_str):
nkfd_form = unicodedata.normalize('NFKD', input_str)
return u"".join([c for c in nkfd_form if not unicodedata.combining(c)])