猿问

如何删除单词末尾的数字?

我想从一个字符串中删除数字,该字符串正好放在单词后面,没有任何空格。例如:


'Senku Ishigami is charecter from a manga series98 onging since 2017.'

应该:


'Senku Ishigami is charecter from a manga series onging since 2017.'

我可以使用正则表达式删除检测数字'[a-z]+[0-9]+',但是当我无法理解如何删除它时。我试图通过编写来删除它'[a-z]',因为我认为它会起作用,但它只是'[a-z]'作为字符串打印。


这是代码:


import re


text ='Senku Ishigami is charecter from a manga series98 onging since 2017.'

text = re.sub(r'[a-z]+[0-9]+', '[a-z]', text)

print(text)

输出:


Senku Ishigami is charecter from a manga [a-z] onging since 2017.


肥皂起泡泡
浏览 114回答 2
2回答

绝地无双

您还可以使用捕获组在匹配 1 个以上数字之前仅捕获单个字符。在替换中使用组 1 使用\1([a-z])\d+\b正则表达式演示import retext ='Senku Ishigami is charecter from a manga series98 onging since 2017.'text = re.sub(r'([a-z])\d+\b', r'\1', text)print(text)输出Senku Ishigami is charecter from a manga series onging since 2017.

一只斗牛犬

您可以使用import retext ='Senku Ishigami is charecter from a manga series98 onging since 2017.'text = re.sub(r'(?<=[a-z])\d+\b', '', text)print(text) # => Senku Ishigami is charecter from a manga series onging since 2017.请参阅正则表达式演示和Python 演示。正则表达式详细信息(?<=[a-z])- 紧邻小写 ASCII 字母的位置\d+- 一位或多位数字\b- 单词边界(数字仅在单词末尾匹配)。
随时随地看视频慕课网APP

相关分类

Python
我要回答