我想在python中删除字符串中的字符:
string.replace(',', '').replace("!", '').replace(":", '').replace(";", '')...
但我有很多字符必须删除。我想了一个清单
list = [',', '!', '.', ';'...]
但是如何使用列表来替换字符串中的字符呢?
我想在python中删除字符串中的字符:
string.replace(',', '').replace("!", '').replace(":", '').replace(";", '')...
但我有很多字符必须删除。我想了一个清单
list = [',', '!', '.', ';'...]
但是如何使用列表来替换字符串中的字符呢?
当前回答
删除* % @ !从下面的字符串:
s = "this is my string, and i will * remove * these ** %% "
new_string = s.translate(s.maketrans('','','*%,&@!'))
print(new_string)
# output: this is my string and i will remove these
其他回答
在Python 3.8中,这适用于我:
s.translate(s.maketrans(dict.fromkeys(',!.;', '')))
简单的方法,
import re
str = 'this is string ! >><< (foo---> bar) @-tuna-# sandwich-%-is-$-* good'
// condense multiple empty spaces into 1
str = ' '.join(str.split()
// replace empty space with dash
str = str.replace(" ","-")
// take out any char that matches regex
str = re.sub('[!@#$%^&*()_+<>]', '', str)
输出:
这是细绳,foo,酒吧,金枪鱼三明治——是——好
删除* % @ !从下面的字符串:
s = "this is my string, and i will * remove * these ** %% "
new_string = s.translate(s.maketrans('','','*%,&@!'))
print(new_string)
# output: this is my string and i will remove these
最近我在钻研scheme,现在我觉得我擅长递归和求值。哈哈哈。分享一些新的方法:
首先,求值
print eval('string%s' % (''.join(['.replace("%s","")'%i for i in replace_list])))
第二,递归
def repn(string,replace_list):
if replace_list==[]:
return string
else:
return repn(string.replace(replace_list.pop(),""),replace_list)
print repn(string,replace_list)
嘿,别投反对票。我只是想分享一些新的想法。
另外一个有趣的话题是将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)])