当前位置:  开发笔记 > 编程语言 > 正文

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

如何解决《Python:删除字符串开头的数字》经验,为你挑选了1个好方法。

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

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> Martijn Piet..:

您可以使用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'

推荐阅读
wangtao
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有