【问题标题】:How to use both isalpha( ) and isdigit( ) to filter out what isn't a letter or digit?如何同时使用 isalpha( ) 和 isdigit( ) 过滤掉不是字母或数字的内容?
【发布时间】:2020-11-19 21:47:49
【问题描述】:

我需要使用 .isalpha() 和 .isdigit() 过滤掉所有不是字母或数字的内容。
目前正在做定义和 .replace()。

This is my program

【问题讨论】:

  • 这两个功能有必要用吗?
  • 你能发布你的代码吗?顺便说一句,isalnum 有一个函数
  • @KarinaK 是的,有人告诉我同时使用 isalpha() 和 is digit()。
  • exit = False takeout =":.;!@#$%^&*()}{|\+=" + " " while exit == False: data = input(("Enter设置或按 E/e 退出:")) data = data.lower() for i in takeout : data = data.replace(i,"") newdata = data[::-1] print("输入向后打印is: ", newdata,"\n") if len(data)

标签: python string loops palindrome isalpha


【解决方案1】:
def remove_special_chars(string):
    output = []
    for c in string:
        if c.isalpha() or c.isdigit();
            output.append(c)
    return ''.join(output)

【讨论】:

    【解决方案2】:

    您可以通过以下方式轻松实现:

    from sets import Set
    
    allowed_chars = Set('0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ')
    validationString = 'inv@lid'
    
    if Set(validationString).issubset(allowed_chars):
        return validationString # nothing to remove from this string
    else:
        return ''.join(i for i in validationString if Set(i).issubset(allowed_chars))
    

    【讨论】:

    【解决方案3】:

    使用正则表达式拆分和过滤以及isdigit和isalpha

     sentence ="1 I have bought several of the Vitality canned dog food products and have found them all to be of good quality. huh? The product looks more like a stew than a processed meat and it smells better-looks better. My Labrador is finicky-pampered and she appreciates this product better than most."
     sentence=sentence.lower()
     words=re.split("[, |-|\?|\!|\.]",sentence)
     words=filter(lambda w: ((w.isdigit() or w.isalpha()) and len(w)>0),words)
     print(*words)
    

    输出:

      1 i have bought several of the vitality canned dog food products and have found them all to be of good quality huh the product looks more like a stew than a processed meat and it smells better my labrador is and she appreciates this product better than most
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-01-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-01-12
      • 1970-01-01
      相关资源
      最近更新 更多