【问题标题】:How to remove digits from the end of a string in Python 3.x?如何从 Python 3.x 中的字符串末尾删除数字?
【发布时间】:2017-04-03 03:40:08
【问题描述】:

我想从字符串末尾删除数字,但我不知道。

split() 方法可以工作吗?我怎样才能做到这一点?

初始字符串看起来像asdfg123,而我只想要asdfg

感谢您的帮助!

【问题讨论】:

标签: python-3.x split


【解决方案1】:

您可以将str.rstrip 与要删除字符串尾随字符的数字字符一起使用:

>>> 'asdfg123'.rstrip('0123456789')
'asdfg'

或者,您可以使用string.digits 代替'0123456789'

>>> import string
>>> string.digits
'0123456789'
>>> 'asdfg123'.rstrip(string.digits)
'asdfg'

【讨论】:

  • 谢谢!!这真的很有帮助!
【解决方案2】:

不,拆分不起作用,因为拆分只能使用固定的字符串进行拆分。

你可以使用str.rstrip() method:

import string

cleaned = yourstring.rstrip(string.digits)

这使用string.digits constant 来方便地定义需要删除的内容。

或者您可以使用正则表达式将末尾的数字替换为空字符串:

import re

cleaned = re.sub(r'\d+$', '', yourstring)

【讨论】:

  • 谢谢!!这真的很有帮助!
【解决方案3】:

正则表达式!

import re
intialString = "asdfg123"
newString = re.search("[^\d]*", intialString).group()
print(newString)

预期结果是“asdfg”。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-11-05
    • 1970-01-01
    • 2011-02-20
    • 2011-03-07
    • 1970-01-01
    相关资源
    最近更新 更多