如何从Python 3.x中删除字符串末尾的数字?

kla*_*wei 4 split python-3.x

我有一个问题.我想从字符串末尾删除数字,但我不知道.可以使用split()方法吗?我怎样才能使它工作?初始字符串就像'asdfg123',并且我只想要'asdfg'.谢谢你的帮助!

Mar*_*ers 14

不,拆分不起作用,因为拆分只能使用固定字符串来拆分.

你可以使用这个str.rstrip()方法:

import string

cleaned = yourstring.rstrip(string.digits)
Run Code Online (Sandbox Code Playgroud)

这使用string.digits常量作为需要删除的内容的方便定义.

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

import re

cleaned = re.sub(r'\d+$', '', yourstring)
Run Code Online (Sandbox Code Playgroud)


fal*_*tru 5

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

>>> 'asdfg123'.rstrip('0123456789')
'asdfg'
Run Code Online (Sandbox Code Playgroud)

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

>>> import string
>>> string.digits
'0123456789'
>>> 'asdfg123'.rstrip(string.digits)
'asdfg'
Run Code Online (Sandbox Code Playgroud)