Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 looks like asdfg123,and I only want asdfg instead.

Thanks for your help!

like image 481
klaine wei Avatar asked Nov 19 '16 09:11

klaine wei


People also ask

How do you remove trailing numbers in Python?

Use the str. rstrip() method to remove the trailing zeros.

How do you remove the last 3 digits in Python?

In python, we can select characters in a string using negative indexing too. Last character in string has index -1 and it will keep on decreasing till we reach the start of the string. So to remove last 3 characters from a string select character from 0 i.e. to -3 i.e.


2 Answers

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)
like image 200
Martijn Pieters Avatar answered Oct 19 '22 11:10

Martijn Pieters


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'
like image 34
falsetru Avatar answered Oct 19 '22 09:10

falsetru