Search code examples
pythonstringsplitnumbersletter

How to check if a string contains letters?


I have a numerical string which sometimes it contains letters. I must delete letters and everything after that from my input string. I have tried:

import re
b = re.split('[a-z]|[A-Z]', a)
b = b[0]

But this returns error whenever the string doesn't contain letters.

Do I need to check if a contains letters before trying to split at their point?

How can I check that?

Two examples:

a = '1234' 

and

a = '1234h'

I want to have b = '1234' after both


Another example:
I want a= '4/200, 3500/ 500 h3m' or a= '4/200, 3500/ 500h3m' to return something like:

b= ['4', '200', '3500', '500']

Solution

  • import re
    match = re.search('^[\d]+', '1234h')
    if match:
        print(match.group(0))
    

    It will return '1234' for '1234' and '1234h'. It find series of digits after starting and ignores after letter.