我有一些像这样的字符串:
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]
方法,但由于字符串的不规则格式我不能使用它?有什么建议?
您可以使用str.lstrip()
以下命令从开头删除所有数字,点,短划线和空格:
string1.lstrip('0123456789.- ')
将参数to 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'