Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

remove numbers string python [duplicate]

Tags:

python

string

For my assignment, I have to create a function that returns a new string that is the same as the given string, but with digits removed.

Example: remove digits(’abc123’) would return the string ’abc’.

I have tried almost everything I can think off but it's not working properly :(

def test(str):
    for ch in str:
        num = ['0', '1', '2', '3', '4', '6', '7', '8', '9']
        if ch == num[0]:
            return str.replace(ch, '')
        elif ch == num[1]:
            return str.replace(ch, '')
        elif ch == num[2]:
            return str.replace(ch, '')
        elif ch == num[3]:
            return str.replace(ch, '')
        elif ch == num[4]:
            return str.replace(ch, '')
        elif ch == num[5]:
            return str.replace(ch, '')
        elif ch == num[6]:
            return str.replace(ch, '')
        elif ch == num[7]:
            return str.replace(ch, '')
        elif ch == num[8]:
            return str.replace(ch, '')

I enter test('abc123'), expecting the output to be 'abc'. But instead I get 'abc23' as my output.

In other attempts, same problem:

def test(str):
    for char in str:
        num = ['0', '1', '2', '3', '4', '6', '7', '8', '9']
        if char in list(num):
            return str.replace(char, '', len(str))

I get the same results.

Can anyone help me? It would be greatly appreciated.

like image 335
MountainSlayer Avatar asked Jun 18 '26 02:06

MountainSlayer


1 Answers

Use regex

import re
def test(str):
    string_no_numbers = re.sub("\d+", " ", str)
    print(string_no_numbers)
test('abc123') #prints abc
like image 185
Rafael Avatar answered Jun 19 '26 17:06

Rafael