在Python中,筛选字符串中的字母和数字可以通过以下几种方法实现:
方法一:使用`str.translate()`和`str.maketrans()`
import string
def filter_letters_digits(text):
创建一个映射表,将标点符号和空格映射为空字符串
trans_table = str.maketrans(string.punctuation + ' ', '')
使用translate方法移除字符串中的标点符号和空格
cleaned_text = text.translate(trans_table)
使用列表推导式筛选出字母和数字
letters_digits = [char for char in cleaned_text if char.isalnum()]
将筛选出的字符连接成字符串并返回
return ''.join(letters_digits)
text = "Hello, World! 123"
print(filter_letters_digits(text)) 输出:HelloWorld123
方法二:使用正则表达式
import re
def filter_characters(text, pattern):
使用正则表达式替换不符合模式的字符为空字符
return re.sub(pattern, '', text)
text = "1123*$ 中abc国"
print(filter_characters(text, r'[^a-zA-Z0-9\u4e00-\u9fa5]')) 输出:中国
方法三:使用`filter()`函数
def filter_digits(text):
保留数字
return ''.join(filter(str.isdigit, text))
def filter_letters(text):
保留字母
return ''.join(filter(str.isalpha, text))
def filter_alphanumeric(text):
保留字母和数字
return ''.join(filter(str.isalnum, text))
crazystring = "dade142.!0142f[., ]ad"
print(filter_digits(crazystring)) 输出:
print(filter_letters(crazystring)) 输出:dadefad
print(filter_alphanumeric(crazystring)) 输出:dadefad
以上方法都可以用来筛选字符串中的字母和数字。选择哪一种方法取决于你的具体需求和对性能的考量