2

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.

123Bear Honey
  • 81
  • 1
  • 6
  • 2
    At the risk of sounding snarky, I'd say you should try writing a function in python to take care of this. For starters, you can iterate over a string and to test whether each character is a number or not.. `for char in myString:` ... – Leroy Jenkins Aug 23 '16 at 19:16
  • Possible duplicate of [Python: Extract numbers from a string](http://stackoverflow.com/questions/4289331/python-extract-numbers-from-a-string) – Gerard Roche Aug 23 '16 at 19:38

2 Answers2

5

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'
alecxe
  • 462,703
  • 120
  • 1,088
  • 1,195
2

Use lstrip:

myString.lstrip('0123456789')

or

import string
myString.lstrip(string.digits)
Daniel
  • 42,087
  • 4
  • 55
  • 81