Remove Numbers String Python
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 r
Solution 1:
Use regex
import re
deftest(str):
string_no_numbers = re.sub("\d+", " ", str)
print(string_no_numbers)
test('abc123') #prints abc
Solution 2:
Use this
string = ''.join([c for c instringif c notin"1234567890"])
Solution 3:
Your second solution is close:
def drop_digits(in_str):
digit_list ="1234567890"forchar 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([charforcharin in_str ifnotchar.isdigit()])
Solution 4:
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, '')
Solution 5:
def test(string):
return''.join((letter for letter in string if not letter.isdigit()))
Post a Comment for "Remove Numbers String Python"