简体   繁体   English

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

[英]Python: Remove numbers at the beginning of a string

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"

You can remove all digits, dots, dashes and spaces from the start using str.lstrip() : 您可以使用str.lstrip()从头开始删除所有数字,点,短划线和空格:

string1.lstrip('0123456789.- ')

The argument to str.strip() is treated as a set , eg 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. str.strip()的参数被视为一个集合 ,例如,除非该字符串不再以这些字符开头,否则将删除作为该集合成员的字符串开头的任何字符。

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'

This is almost the same as @MartijnPieters' answer but we could use constants from string<\/code> module if there are a lot of punctuation and whitespace characters to strip on top of digits:这与@MartijnPieters 的答案几乎相同,但如果在数字顶部有很多标点符号和空格字符,我们可以使用string<\/code>模块中的常量:

import string
nonalpha = string.digits + string.punctuation + string.whitespace
out = some_string.lstrip(nonalpha)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM