python字符串只保留数字和字母

2023-11-19 09:25:16

你可以使用正则表达式来过滤字符串中的非字母和数字字符。以下是一个示例代码:

import re

def keep_alphanumeric(string):
    pattern = re.compile(r'[W_]+')
    return re.sub(pattern, '', string)

# 示例用法
string = 'Hello World! 123'
filtered_string = keep_alphanumeric(string)
print(filtered_string)  # 输出: HelloWorld123

在上述代码中,`re.compile(r'[W_]+')`定义了一个正则表达式模式,该模式可以匹配任何非字母和数字字符。`re.sub(pattern, '', string)`将字符串中的非字母和数字字符替换为空字符串,从而实现了只保留字母和数字的效果。