如何从一个单词的开头删除任意数量的非字母符号?

2024-09-24 00:25:21 发布

您现在位置: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)

有什么建议吗


Tags: inimportreforapplication字母setupoperating
1条回答
网友
1楼 · 发布于 2024-09-24 00:25:21

你可以用

import re
re.sub(r"^[\W\d_]+", "", w)

使用PyPi ^{} module,您可以使用

import regex
regex.sub(r"^\P{L}+", "", w)

详细信息

  • ^-字符串的开头(此处与\A相同)
  • [\W\d_]+-匹配任何非单词、数字或下划线字符
  • \P{L}+-除任何Unicode字母外的一个或多个字符

见a Python demo

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

相关问题 更多 >