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

2024-04-25 17:08:41 发布

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

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

This is my program


Tags: 内容定义ismy字母数字thisprogram
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
def remove_special_chars(string):
    output = []
    for c in string:
        if c.isalpha() or c.isdigit();
            output.append(c)
    return ''.join(output)

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

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

相关问题 更多 >