123Bear Honey
123Bear Honey

Reputation: 81

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:

"cl2"

I need it to work for any length of number, so 2h2 should become h2, 4563nh3 becomes nh3 etc. EDIT: This has numbers without spaces between so it is not the same as the other question and it is specifically the first numbers, not all of the numbers.

Upvotes: 2

Views: 882

Answers (2)

Daniel
Daniel

Reputation: 42758

Use lstrip:

myString.lstrip('0123456789')

or

import string
myString.lstrip(string.digits)

Upvotes: 2

alecxe
alecxe

Reputation: 473863

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

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

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

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

Upvotes: 5

Related Questions