使用python中的给定列表删除字符串中的特定字符

2024-07-08 14:35:03 发布

您现在位置:Python中文网/ 问答频道 /正文

punctuation_chars = ["'", '"', ",", ".", "!", ":", ";", '#', '@']
def strip_punctuation(x):
    for i in punctuation_chars:
        for i in x:
            if x=="i":
                x.replace("i","")
                return x
m= "Twi@sd"
t=strip_punctuation(m)
print(t)

我正在尝试使用上述代码删除字符串中的特定字符。这里的问题是什么


Tags: 字符串代码inforreturnifdefsd
3条回答

字符串是不可变的。因此,您希望将其重新分配。 i是一个变量。通过使用"i",它被视为一个字符串。 试一试

punctuation_chars = ["'", '"', ",", ".", "!", ":", ";", '#', '@']
def strip_punctuation(x):
    for i in punctuation_chars:
        if i in x:
           x= x.replace(i,"")
    return x

m= "Twi@sd"
t=strip_punctuation(m)
print(t)

循环通过punctuation_chars并替换每个字符

def strip_punctuation(x):
    for c in punctuation_chars:      
        x = x.replace(c, "")
    return x

str.replace()返回一个新字符串,因此每次都必须将其分配给一个新变量(python字符串是不可变的)

Replace方法不是就地方法,需要将值存储到变量中才能使用它

为此,也不需要内部循环

查看解决方案,如果有任何疑问,请发表评论

代码:

punctuation_chars = ["'", '"', ",", ".", "!", ":", ";", '#', '@']
def strip_punctuation(x):
    for i in punctuation_chars:
        if i in x:
            x=x.replace(i, '')
    return x

m= "Twi@s:d"
t=strip_punctuation(m)
print(t)

输出:

Twisd

相关问题 更多 >

    热门问题