我想在python中删除字符串中的字符:
string.replace(',', '').replace("!", '').replace(":", '').replace(";", '')...
但我有很多字符必须删除。我想了一个清单
list = [',', '!', '.', ';'...]
但是如何使用列表来替换字符串中的字符呢?
我想在python中删除字符串中的字符:
string.replace(',', '').replace("!", '').replace(":", '').replace(";", '')...
但我有很多字符必须删除。我想了一个清单
list = [',', '!', '.', ';'...]
但是如何使用列表来替换字符串中的字符呢?
当前回答
您可以使用翻译方法。
s.translate(None, '!.;,')
其他回答
另一种使用regex的方法:
''.join(re.split(r'[.;!?,]', s))
为什么不是一个简单的循环?
for i in replace_list:
string = string.replace(i, '')
另外,避免将列表命名为“list”。它覆盖内置函数列表。
简单的方法,
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,酒吧,金枪鱼三明治——是——好
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'
下面是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'
在这里,我们将在黑名单中找到的项目进行拆分,将结果平直并连接字符串。