【问题标题】:How to extract the first numbers in a string - Python如何提取字符串中的第一个数字 - Python
【发布时间】:2016-08-23 19:10:50
【问题描述】:

如何删除字符串中第一个字母之前的所有数字?例如,

myString = "32cl2"

我希望它变成:

"cl2"

我需要它适用于任何长度的数字,所以 2h2 应该变成 h2,4563nh3 变成 nh3 等等。 编辑: 这有数字之间没有空格,因此它与其他问题不同,它特别是第一个数字,而不是所有数字。

【问题讨论】:

  • 冒着听起来刺耳的风险,我想说你应该尝试在 python 中编写一个函数来解决这个问题。对于初学者,您可以遍历字符串并测试每个字符是否为数字。for char in myString: ...

标签: python string numbers truncate


【解决方案1】:

如果你要在没有正则表达式的情况下解决它,你可以使用itertools.dropwhile()

>>> from itertools import dropwhile
>>>
>>> ''.join(dropwhile(str.isdigit, "32cl2"))
'cl2'
>>> ''.join(dropwhile(str.isdigit, "4563nh3"))
'nh3'

或者,使用re.sub(),替换字符串开头的一个或多个数字:

>>> import re
>>> re.sub(r"^\d+", "", "32cl2")
'cl2'
>>> re.sub(r"^\d+", "", "4563nh3")
'nh3'

【讨论】:

  • 干杯,伙计,会给你竖起大拇指,但我不能!
【解决方案2】:

使用lstrip:

myString.lstrip('0123456789')

import string
myString.lstrip(string.digits)

【讨论】:

  • 我比选择的答案更喜欢这个,因为它更简单。
猜你喜欢
  • 1970-01-01
  • 2021-07-06
  • 1970-01-01
  • 2014-06-12
  • 1970-01-01
  • 2022-11-02
  • 2011-10-29
  • 1970-01-01
  • 2022-12-20
相关资源
最近更新 更多