Python:删除字符串开头的数字

时间:2015-12-10 12:06:35

标签: python regex string string-split

我有一些像这样的字符串:

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"

我需要从字符串的开头删除这些数字。我试过strip[start: end]方法,但由于字符串格式不规则我无法使用它?有什么建议?

1 个答案:

答案 0 :(得分:17)

您可以使用str.lstrip()

从头开始删除所有数字,点,短划线和空格
string1.lstrip('0123456789.- ')

str.strip()的参数被视为,例如将删除作为该集合成员的字符串开头的任何字符,直到该字符串不再以这些字符开头。

演示:

>>> 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'