How to remove digits from the end of a string in Python 3.x?

拥有回忆 提交于 2020-06-25 23:21:30

问题


i've got a problem.I want to remove digits from the end of a string,but i have no idea.Can the split() method work?How can i make that work?The initial string is like 'asdfg123',and i only want 'asdfg' instead.Thanks for your help!


回答1:


No, split would not work, because split only can work with a fixed string to split on.

You could use the str.rstrip() method:

import string

cleaned = yourstring.rstrip(string.digits)

This uses the string.digits constant as a convenient definition of what needs to be removed.

or you could use a regular expression to replace digits at the end with an empty string:

import re

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



回答2:


You can use str.rstrip with digit characters you want to remove trailing characters of the string:

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

Alternatively, you can use string.digits instead of '0123456789':

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


来源:https://stackoverflow.com/questions/40691451/how-to-remove-digits-from-the-end-of-a-string-in-python-3-x

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!