问题
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?
回答1:
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'
来源:https://stackoverflow.com/questions/34201490/python-remove-numbers-at-the-beginning-of-a-string