python - 如何从单词的开头删除任意数量的非字母符号?
问题描述
我有以下几句话:
words = ['001operating', '1002application', '3aaa0225', '-setup', '--setup']
我需要在单词之前删除任何非字母字符。预期的结果是这样的:
processed = ['operating', 'application', 'aaa0225', 'setup', 'setup']
这是我到目前为止所拥有的:
import re
processed = []
for w in words:
w = re.sub(r"(?<!\S)", "", w)
processed.append(w)
有什么建议么?
解决方案
您可以使用
import re
re.sub(r"^[\W\d_]+", "", w)
使用PyPiregex
模块,您可以使用
import regex
regex.sub(r"^\P{L}+", "", w)
细节
^
- 字符串的开头(此处,与 相同\A
)[\W\d_]+
- 匹配任何非单词、数字或下划线字符\P{L}+
- 一个或多个字符,而不是任何 Unicode 字母。
查看Python 演示:
import re, regex
words =['001operating', '1002application', '3aaa0225', '-setup', '--setup']
print( [re.sub(r"^[\W\d_]+", "", w) for w in words] )
# => ['operating', 'application', 'aaa0225', 'setup', 'setup']
print( [regex.sub(r"^\P{L}+", "", w) for w in words] )
# => ['operating', 'application', 'aaa0225', 'setup', 'setup']
推荐阅读
- java - Google 视觉响应标签未以原始 JSON 格式返回
- menu - 我可以在这个子菜单的顶部添加一个“编辑过滤器”吗?
- javascript - 制表符 打印点击的行 - 打印 PDF?
- scala - 使用通配符类型参数化的 Scala 案例类成员在调用时不会推断类型绑定
- botium-box - 如何在 botium 中发送有效的正则表达式
- python - Python3:如何“不”舍入到最接近的偶数?
- javascript - JS 均匀地减少一个数组
- javascript - setTimeout 不会产生正确的异步行为
- excel - 有没有办法从公式中提取公式结果以对其进行进一步的数学运算?
- python - 什么是在 Numpy 中将总和从 i = 1 写入 n, log(1 + exp(w_i)) 的有效方法