Search code examples
pythonstrip

Stripping numbers dates until first alphabet is found from string


I am trying an efficient way to strip numbers dates or any other characters present in a string until the first alphabet is found from the end.

string - '12.abd23yahoo 04/44 231'
Output - '12.abd23yahoo'

line_inp = "12.abd23yahoo 04/44 231"
line_out = line_inp.rstrip('0123456789./') 

This rstrip() call doesn't seem to work as expected, I get '12.abd23yahoo 04/44 ' instead.

I am trying below and it doesn't seem to be working.

for fname in filenames:
with open(fname) as infile:
    for line in infile:
        outfile.write(line.rstrip('0123456789./ '))

Solution

  • Here's a solution using a regular expression:

    import re    
    line_inp = "12.abd23yahoo 04/44 231"
    r = re.compile('^(.*[a-zA-Z])')
    m = re.match(r, line_inp)
    line_out = m.group(0) # 12.abd23yahoo
    

    The regular expression matches a group of arbitrary characters which end in a letter.