我想在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
其他回答
为什么不是一个简单的循环?
for i in replace_list:
string = string.replace(i, '')
另外,避免将列表命名为“list”。它覆盖内置函数列表。
你可以用这样的东西
def replace_all(text, dic):
for i, j in dic.iteritems():
text = text.replace(i, j)
return text
这不是我自己的代码,来自这里,这是一篇伟大的文章,并深入讨论了这样做
下面是more_itertools的方法:
import more_itertools as mit
s = "A.B!C?D_E@F#"
blacklist = ".!?_@#"
"".join(mit.flatten(mit.split_at(s, pred=lambda x: x in set(blacklist))))
# 'ABCDEF'
在这里,我们将在黑名单中找到的项目进行拆分,将结果平直并连接字符串。
最近我在钻研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)
嘿,别投反对票。我只是想分享一些新的想法。
如果您正在使用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'