首页 > 解决方案 > 如何从单词的开头删除任意数量的非字母符号?

问题描述

我有以下几句话:

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)

有什么建议么?

标签: pythonregex

解决方案


您可以使用

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']

推荐阅读