123Bear Honey 123Bear Honey - 1 year ago 60
Python Question

How to extract the first numbers in a string - Python

How do I remove all the numbers before the first letter in a string? For example,

myString = "32cl2"

I want it to become:


I need it to work for any length of number, so 2h2 should become h2, 4563nh3 becomes nh3 etc.

Answer Source

If you were to solve it without regular expressions, you could have used itertools.dropwhile():

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

Or, using re.sub(), replacing one or more digits at the beginning of a string:

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