我试图使用Python从字符串中删除特定字符。这是我现在使用的代码。不幸的是,它似乎对字符串没有做任何事情。

for char in line:
    if char in " ?.!/;:":
        line.replace(char,'')

我如何正确地做到这一点?


当前回答

用re.sub正则表达式

从Python 3.5开始,可以使用正则表达式re.sub进行替换:

import re
re.sub('\ |\?|\.|\!|\/|\;|\:', '', line)

例子

import re
line = 'Q: Do I write ;/.??? No!!!'
re.sub('\ |\?|\.|\!|\/|\;|\:', '', line)

'QDoIwriteNo'

解释

在正则表达式(regex)中,|是一个逻辑或,\转义可能是实际的正则表达式命令的空格和特殊字符。而sub代表替换,在这种情况下是空字符串”。

其他回答

这是我的Python 2/3兼容版本。因为翻译api已经改变了。

def remove(str_, chars):
    """Removes each char in `chars` from `str_`.

    Args:
        str_: String to remove characters from
        chars: String of to-be removed characters

    Returns:
        A copy of str_ with `chars` removed

    Example:
            remove("What?!?: darn;", " ?.!:;") => 'Whatdarn'
    """
    try:
        # Python2.x
        return str_.translate(None, chars)
    except TypeError:
        # Python 3.x
        table = {ord(char): None for char in chars}
        return str_.translate(table)

您还可以使用函数来替换不同类型的正则表达式或使用列表的其他模式。这样,您就可以混合正则表达式、字符类和真正基本的文本模式。当您需要替换大量元素(如HTML元素)时,它非常有用。

*注意:适用于Python 3.x

import re  # Regular expression library


def string_cleanup(x, notwanted):
    for item in notwanted:
        x = re.sub(item, '', x)
    return x

line = "<title>My example: <strong>A text %very% $clean!!</strong></title>"
print("Uncleaned: ", line)

# Get rid of html elements
html_elements = ["<title>", "</title>", "<strong>", "</strong>"]
line = string_cleanup(line, html_elements)
print("1st clean: ", line)

# Get rid of special characters
special_chars = ["[!@#$]", "%"]
line = string_cleanup(line, special_chars)
print("2nd clean: ", line)

在函数string_cleanup中,它以字符串x和未修饰的列表作为参数。对于元素或模式列表中的每一项,如果需要替代品,就会进行替换。

输出:

Uncleaned:  <title>My example: <strong>A text %very% $clean!!</strong></title>
1st clean:  My example: A text %very% $clean!!
2nd clean:  My example: A text very clean

即使是下面的方法也是有效的

line = "a,b,c,d,e"
alpha = list(line)
        while ',' in alpha:
            alpha.remove(',')
finalString = ''.join(alpha)
print(finalString)

输出:中的

对于只允许字符串中某些字符的相反要求,可以使用带有集补操作符[^ABCabc]的正则表达式。例如,要删除除ascii字母、数字和连字符以外的所有字符:

>>> import string
>>> import re
>>>
>>> phrase = '  There were "nine" (9) chick-peas in my pocket!!!      '
>>> allow = string.letters + string.digits + '-'
>>> re.sub('[^%s]' % allow, '', phrase)

'Therewerenine9chick-peasinmypocket'

来自python正则表达式文档:

不在范围内的字符可以通过互补来匹配 一组。如果集合的第一个字符是'^',则所有字符 不在集合中的将被匹配。例如,[^5]将匹配 除'5'以外的任何字符,[^^]将匹配除 “^”。的第一个字符没有特殊意义 集。

提问者几乎就说到了。像Python中的大多数事情一样,答案比您想象的要简单。

>>> line = "H E?.LL!/;O:: "  
>>> for char in ' ?.!/;:':  
...  line = line.replace(char,'')  
...
>>> print line
HELLO

你不需要做嵌套的if/for循环,但你确实需要单独检查每个字符。