如何同时使用 isalpha( ) 和 isdigit( ) 来过滤掉不是字母或数字的内容?

问题描述 投票:0回答:3

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

这是我的程序

python string loops palindrome isalpha
3个回答
1
投票
def remove_special_chars(string):
    output = []
    for c in string:
        if c.isalpha() or c.isdigit():
            output.append(c)
    return ''.join(output)

0
投票

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

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))

0
投票

使用正则表达式分割和过滤以及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
© www.soinside.com 2019 - 2024. All rights reserved.