3

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.

Pax Vobiscum
  • 2,551
  • 2
  • 21
  • 32
MountainSlayer
  • 291
  • 1
  • 5
  • 14

5 Answers5

9

Use regex

import re
def test(str):
    string_no_numbers = re.sub("\d+", " ", str)
    print(string_no_numbers)
test('abc123') #prints abc
Rafael
  • 3,096
  • 1
  • 23
  • 61
2

Use this

string = ''.join([c for c in string if c not in "1234567890"])
Pax Vobiscum
  • 2,551
  • 2
  • 21
  • 32
1

Your second solution is close:

def drop_digits(in_str):
    digit_list = "1234567890"
    for char in digit_list:
        in_str = in_str.replace(char, "")

    return in_str

The original problem is that you return after replacing only the '1' chars.

You can also do this with a list comprehension:

return ''.join([char for char in in_str if not char.isdigit()])
Prune
  • 76,765
  • 14
  • 60
  • 81
0

You need to read up on some python basics. The "return" exits your function, so it will only ever modify one entry.

Here's a hint: replace str with an updated copy instead of returning it.

str = str.replace(ch, '')
jaypb
  • 1,544
  • 10
  • 23
-1
def test(string):
    return ''.join((letter for letter in string if not letter.isdigit()))
Nf4r
  • 1,390
  • 1
  • 7
  • 9