24

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!

Pedram Parsian
  • 3,750
  • 3
  • 19
  • 34
klaine wei
  • 273
  • 1
  • 2
  • 4

3 Answers3

51

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)
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
9

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'
falsetru
  • 357,413
  • 63
  • 732
  • 636
0

Regex!

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

Expected Outcome is "asdfg".

Cade Bray
  • 1
  • 1