【问题标题】:Python: Remove numbers at the beginning of a stringPython:删除字符串开头的数字
【发布时间】:2016-03-16 01:33:27
【问题描述】:

我有一些这样的字符串:

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] 方法,但由于字符串格式不规则,我无法使用它?有什么建议?

【问题讨论】:

  • 应该去掉标点吗?
  • 在删除了数字和标点符号之后,空格会发生什么?也许您可以在您的问题中添加一些预期的输出

标签: python regex string string-split


【解决方案1】:

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

【讨论】:

  • 我没有提到字符串中还有我不想删除的数字,这将删除所有?
  • @EstinaEsitna:这只从一开始就删除了论文。不是来自其他任何地方。
  • 你能告诉我为什么正则表达式不能替换lstrip()。我正在尝试string1.lstrip(r'(\d+(.|-|\s)?)+')
  • @RohanAmrute:为什么会这样?它不接受正则表达式,它接受一组单独的字符。将re 模块用于正则表达式。
  • @RohanAmrute:import re 然后re.sub(r'^[\d.-]+\s*', '', string1)
猜你喜欢
  • 2015-01-28
  • 1970-01-01
  • 2019-11-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-11-13
  • 2013-10-30
相关资源
最近更新 更多