如何提取字符串中的第一个数字 - Python

How to extract the first numbers in a string - Python

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

myString = "32cl2"

我希望它变成:

"cl2"

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

如果你不使用正则表达式来解决它,你可以使用 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'

使用lstrip:

myString.lstrip('0123456789')

import string
myString.lstrip(string.digits)