Python: Remove numbers at the beginning of a string

牧云@^-^@ 提交于 2019-12-10 17:53:43

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!