【问题标题】:How can we replace other characters like alphabets and punctuations from a string with empty string(like this '') in Python? [duplicate]我们如何在 Python 中用空字符串(如'')替换字符串中的其他字符,如字母和标点符号? [复制]
【发布时间】:2021-10-10 16:09:09
【问题描述】:

我们如何从 Python 中的字符串中删除或替换一些其他特殊字符,例如字母和标点符号?我曾想过使用string.ascii_lettersstring.punctuation 检查特殊字符,但它对我不起作用。我只想取从 0 到 9 的数字,而不是如果用户输入一个特殊字符,那么它需要用空替换(像这样--> '')。那么,有什么办法可以替代它们呢?

这是我的 Python 代码:

import string

mobile_no = '12aA%!@h34567890'
alpha_characters = list(string.ascii_letters)
special_characters = list(string.punctuation)

if alpha_characters in mobile or special_characters in mobile:
    corrected = mobile_no.replace(alpha_characters, '')
    corrected = mobile_no.replace(special_characters, '')
    print(corrected)

如果我错了,请纠正我

【问题讨论】:

    标签: python python-3.x


    【解决方案1】:

    你需要循环:

    other_characters = string.ascii_letters + string.punctuation
    corrected = mobile_no[:]
    for char in other_characters:
        corrected = corrected.replace(char, '')
    print(corrected)
    

    我愿意:

    other_characters = string.ascii_letters + string.punctuation
    corrected = ''.join([i for i in mobile_no if i not in other_characters])
    

    或者正如@matle 提到的:

    corrected = "".join([f for f in mobile_no if f in "1234567890"])
    

    【讨论】:

    • 或硬编码:"".join([f for f in mobile_no if f in "1234567890"])
    • @U12-Forward 是的,我做到了。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-11-22
    • 2012-09-08
    • 1970-01-01
    • 2018-08-01
    • 2017-05-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多