Utopion
Utopion

Reputation: 1128

Python: remove last number of a string

I need 4 lines of code to do this script but I think it's possible to do it in 2 (maybe even 1 ! let's dream). Do someone has a solution ? You can test the code to see the expected result.

def remove_nbr_at_the_end_of_the_string(my_str):
    while my_str[-1] in ["0", "1", "2", "3" ,"4" ,"5" ,"6" ,"7" ,"8" ,"9"]:
        my_str = my_str[:-1]
    if my_str[-1] == " ": my_str = my_str[:-1]
    return my_str


for text in ["ACCDS 122", "GR DDF 0332", "MLMD 12 334", "MMED DFE"]:
    print(remove_nbr_at_the_end_of_the_string(text))

Upvotes: 0

Views: 1409

Answers (6)

Matthew Muller
Matthew Muller

Reputation: 333

If you're truly adamant about one-lining it without using rstrip:

print("\n".join([string[:len(string)-len(([string[len(string)-i:] for i in range(1, len(string)) if string[len(string)-i:].isdigit()] or [""])[-1])].strip() for string in ["ACCDS 122", "GR DDF 0332", "MLMD 12 334", "MMED DFE"]]))

output:

ACCDS
GR DDF
MLMD 12
MMED DFE

This method creates a list of an expanding window of characters from the right-hand side if they satisfy str.is_digit(), then takes the last element (the biggest valid digit string) of that expanding window list and uses the length of the longest valid digit string to slice the original string. The string is then stripped of whitespace.

There is a particularly sneaky part of this one-liner that makes use of tuple conditional element creation e.g.:

([] or [""])

Which takes the second element if the first element is false.

Upvotes: 0

devReddit
devReddit

Reputation: 2947

If you want to remove all the occurences of numbers in the end of the string, you can do as follows:

def remove_nbr_at_the_end_of_the_string(my_str):
    return [' '.join([j.rstrip('0123456789') for j in i.split()]).strip() for i in my_str]

text = ["ACCDS 122", "GR DDF 0332", "MLMD 12 334", "MMED DFE"]
print(remove_nbr_at_the_end_of_the_string(text))

And you'll get:

['ACCDS', 'GR DDF', 'MLMD', 'MMED DFE']

Upvotes: 0

Ahmar Shoeb
Ahmar Shoeb

Reputation: 89

Use this to remove last number as well as space from the end.

my_str.rstrip('0123456789').strip()

Upvotes: 1

Metapod
Metapod

Reputation: 416

As mentioned in comments, rstrip works pretty well. If you want to create your own rstrip function without any method/other library, something like that can be done too:

def my_rstrip(my_str):
    if(my_str[-1] in ("1","2","3","4","5","6","7","8","9","0"," ")): return my_rstrip(my_str[:-1])
    return my_str

my_str = "123456qweqsd789 65"
print(my_rstrip(my_str))
>> 123456qweqsd

A bit of recursive function never hurts ! (... If your string is not too long i guess ?)

Upvotes: 0

Flo
Flo

Reputation: 487

You can do it using regex

import re

def remove_nbr_at_the_end_of_the_string(my_str):
  found_numbers = re.findall(r'\d+', my_str)
  return my_str.replace(found_numbers[-1], "") if (found_numbers) else my_str

this looks for numbers, starting at the end using "r". if it finds any it will remove the first (from behind), else the string will be returned as it is.

Upvotes: 0

sj95126
sj95126

Reputation: 6908

You can do it in one line with a regular expression (well, two, for the import re):

import re

for text in ["ACCDS 122", "GR DDF 0332", "MLMD 12 334", "MMED DFE"]:
    print(re.sub(r" ?\d+$", "", text))

which produces:

ACCDS
GR DDF
MLMD 12
MMED DFE

Note the space before the ?. That will limit it to removing only one number, plus the space, if there is one. You can replace with \s if you want to expand to other forms of whitespace, like tabs.

Also note that, as written, this will remove anything considered a digit in Unicode. If you want to restrict to 0-9, use this:

re.sub(r" ?\d+$", "", text, re.ASCII)

And as a future FYI, your while loop condition could be simplified to:

while my_str[-1] in "0123456789":

Upvotes: 2

Related Questions