繁体   English   中英

python:如何删除某些字符

[英]python: how to remove certain characters

我如何编写一个函数removeThese(stringToModify,charsToRemove),它将返回一个字符串,该字符串是原始的stringToModify字符串,其中charsToRemove中的字符已从中删除。

>>> s = 'stringToModify'
>>> rem = 'oi'
>>> s.translate(str.maketrans(dict.fromkeys(rem)))
'strngTMdfy'
>>> string_to_modify = 'this is a string'
>>> remove_these = 'aeiou'
>>> ''.join(x for x in string_to_modify if x not in remove_these)
'ths s  strng'

这是一个使用lambda函数和python filter()方法的机会。 filter接受谓词和序列,并返回一个序列,该序列仅包含谓词为true的原始序列中的那些项。 在这里,我们只想要s所有字符都不在rm

>>> s = "some quick string 2 remove chars from"
>>> rm = "2q"
>>> filter(lambda x: not (x in rm), s)
"some uick string remove chars from"
>>>

使用正则表达式:

import re
newString = re.sub("[" + charsToRemove + "]", "", stringToModify)

作为一个具体的例子,以下将从句子中删除所有出现的“a”,“m”和“z”:

import re
print re.sub("[amz]", "", "the quick brown fox jumped over the lazy dog")

这将删除“m”到“s”中的所有字符:

re.sub("[m-s]", "", "the quick brown fox jumped over the lazy dog")

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM