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

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

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


当前回答

你可以使用re模块的正则表达式替换。使用^表达式可以准确地从字符串中选择想要的内容。

    import re
    text = "This is absurd!"
    text = re.sub("[^a-zA-Z]","",text) # Keeps only Alphabets
    print(text)

输出结果将是“这是荒谬的”。只有在^符号之后指定的内容才会出现。

其他回答

试试这个:

def rm_char(original_str, need2rm):
    ''' Remove charecters in "need2rm" from "original_str" '''
    return original_str.translate(str.maketrans('','',need2rm))

这个方法在python3中很有效

这个怎么样:

def text_cleanup(text):
    new = ""
    for i in text:
        if i not in " ?.!/;:":
            new += i
    return new

字符串在Python中是不可变的。replace方法在替换后返回一个新字符串。试一试:

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

这与您的原始代码相同,只是在循环中添加了对line的赋值。

注意,字符串replace()方法会替换字符串中出现的所有字符,因此可以对想要删除的每个字符使用replace(),而不是遍历字符串中的每个字符,这样做会更好。

这里有一些可能的方法来完成这个任务:

def attempt1(string):
    return "".join([v for v in string if v not in ("a", "e", "i", "o", "u")])


def attempt2(string):
    for v in ("a", "e", "i", "o", "u"):
        string = string.replace(v, "")
    return string


def attempt3(string):
    import re
    for v in ("a", "e", "i", "o", "u"):
        string = re.sub(v, "", string)
    return string


def attempt4(string):
    return string.replace("a", "").replace("e", "").replace("i", "").replace("o", "").replace("u", "")


for attempt in [attempt1, attempt2, attempt3, attempt4]:
    print(attempt("murcielago"))

附注:在使用" ?.!/;:"的例子中使用元音…是的,“murcielago”在西班牙语里是蝙蝠的意思…有趣的单词,因为它包含了所有的元音:)

PS2:如果你对性能感兴趣,你可以用一个简单的代码来衡量这些尝试:

import timeit


K = 1000000
for i in range(1,5):
    t = timeit.Timer(
        f"attempt{i}('murcielago')",
        setup=f"from __main__ import attempt{i}"
    ).repeat(1, K)
    print(f"attempt{i}",min(t))

在我的盒子里,你会得到:

attempt1 2.2334518376057244
attempt2 1.8806643818474513
attempt3 7.214925774955572
attempt4 1.7271184513757465

因此,对于这个特定的输入,尝试4似乎是最快的。

使用过滤器,你只需要一行

line = filter(lambda char: char not in " ?.!/;:", line)

这将字符串视为可迭代对象,如果lambda返回True,则检查每个字符:

> > >帮助(过滤器) 模块__builtin__中内置函数过滤器的帮助: 过滤器(…) filter(function或None, sequence) ->列表、元组或字符串 返回函数(item)为true的序列项。如果 函数为None,返回为true的项。If sequence是一个元组 或者字符串,返回相同的类型,否则返回一个列表。