在 Python 中从给定字符串中仅提取字符
pythonserver side programmingprogramming更新于 2025/11/23 19:56:17
一段数据可能包含字母、数字以及特殊字符。如果我们只想从该数据字符串中提取字母,那么我们可以使用 Python 中提供的各种选项。
使用 isalpha
isalpha 函数将检查给定字符是否为字母。我们将在 for 循环中使用它,该循环将从给定字符串中获取每个字符并检查它是否为字母。join 方法将仅将有效字符捕获到结果中。
示例
stringA = "Qwer34^&t%y"
# 给定字符串
print("Given string : ", stringA)
# 查找字符
res = ""
for i in stringA:
if i.isalpha():
res = "".join([res, i])
# 结果
print("Result: ", res)
输出
运行上述代码得到以下结果 −
Given string : Qwer34^&t%y Result: Qwerty
使用正则表达式
我们可以利用正则表达式模块并使用 findall 函数给出仅代表字符的参数值。
示例
import re
stringA = "Qwer34^&t%y"
# 给定字符串
print("Given string : ", stringA)
# 查找字符
res = "".join(re.findall("[a-zA-Z]+", stringA))
# 结果
print("Result: ", res)
输出
运行上述代码得到以下结果 −
Given string : Qwer34^&t%y Result: Qwerty
相关文章
有用资源
python 参考教程 - 该教程包含有关 python 的更多信息:https://www.cainiaomax.com/python/

