Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Remove numbers at the beginning of a string

I have some strings like this:

string1 = "123.123.This is a string some other numbers"
string2 = "1. This is a string some numbers"
string3 = "12-3-12.This is a string 123"
string4 = "123-12This is a string 1234"

I need to remove these numbers from the beginning of the string. I tried strip[start: end] method but because of the irregular format of the string I cant use it? any suggestions?

like image 894
Estina Esitna Avatar asked Dec 10 '15 12:12

Estina Esitna


1 Answers

You can remove all digits, dots, dashes and spaces from the start using str.lstrip():

string1.lstrip('0123456789.- ')

The argument to str.strip() is treated as a set, e.g. any character at the start of the string that is a member of that set is removed until the string no longer starts with such characters.

Demo:

>>> samples = """\
... 123.123.This is a string some other numbers
... 1. This is a string some numbers
... 12-3-12.This is a string 123
... 123-12This is a string 1234
... """.splitlines()
>>> for sample in samples:
...     print 'From: {!r}\nTo:   {!r}\n'.format(
...         sample, sample.lstrip('0123456789.- '))
...
From: '123.123.This is a string some other numbers'
To:   'This is a string some other numbers'

From: '1. This is a string some numbers'
To:   'This is a string some numbers'

From: '12-3-12.This is a string 123'
To:   'This is a string 123'

From: '123-12This is a string 1234'
To:   'This is a string 1234'
like image 89
Martijn Pieters Avatar answered Sep 17 '22 16:09

Martijn Pieters