我想在python中删除字符串中的字符:
string.replace(',', '').replace("!", '').replace(":", '').replace(";", '')...
但我有很多字符必须删除。我想了一个清单
list = [',', '!', '.', ';'...]
但是如何使用列表来替换字符串中的字符呢?
我想在python中删除字符串中的字符:
string.replace(',', '').replace("!", '').replace(":", '').replace(";", '')...
但我有很多字符必须删除。我想了一个清单
list = [',', '!', '.', ';'...]
但是如何使用列表来替换字符串中的字符呢?
当前回答
这个怎么样,一行字。
reduce(lambda x,y : x.replace(y,"") ,[',', '!', '.', ';'],";Test , , !Stri!ng ..")
其他回答
''.join(c for c in myString if not c in badTokens)
另外一个有趣的话题是将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)])
我在想一个解决办法。首先,我将字符串输入作为一个列表。然后我将替换列表中的项。然后通过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)
这将删除字符串中的任何内容。你怎么看?
在Python 3.8中,这适用于我:
s.translate(s.maketrans(dict.fromkeys(',!.;', '')))
也许有一种更现代、更实用的方式来实现你的愿望:
>>> subj = 'A.B!C?'
>>> list = set([',', '!', '.', ';', '?'])
>>> filter(lambda x: x not in list, subj)
'ABC'
请注意,对于这个特定的目的,它是相当夸张的,但一旦您需要更复杂的条件,过滤器就会派上用场