How can I remove digits from a string?
-
43With `re`: `result = re.sub(r'[0-9]+', '', s)` – Wiktor Stribiżew Sep 12 '17 at 09:42
-
with regex you will need to add \. also, as it can be decimal number i think. like result = re.sub(r'[0-9\.]+', '', s) – GurhanCagin Jan 16 '19 at 08:16
-
6`"\d"` is the same in a regex as `"[0-9]"`, so you can do `result = re.sub(r"\d+", "", s)` instead. Speed will probably depend on the particular string being used, but for me, `re.sub` took about twice as long as `str.translate` (slightly longer if you don't use a pre-compiled pattern). – Nathan Jul 05 '19 at 13:24
-
@WiktorStribiżew, you answer is working fine but it is adding a new line in the file. Any reason? – Lakshmi Yadav Sep 14 '20 at 10:55
-
2@LakshmiYadav `re.sub(r'[0-9]+', '', s)` **removes** found matches (see the second argument that is an empty string), it can't add anything. Check your code. – Wiktor Stribiżew Sep 14 '20 at 10:57
-
@WiktorStribiżew, I have 4 line of numeric and alphanumeric strings in a file, I am using for loop and adding your line of code. `import fileinput import re for line in fileinput.input("/Users/xyz/Desktop/temp/i_tmp.txt", inplace=True): print re.sub(r'\b[0-9\.]+','', line)` Once I run above code, numbers are vanished but after every line new line is been added. – Lakshmi Yadav Sep 14 '20 at 11:03
-
@LakshmiYadav It has nothing to do with my regex. Check your `print`. – Wiktor Stribiżew Sep 14 '20 at 11:05
-
This should instead be a duplicate of the much better-asked https://stackoverflow.com/questions/15754587. – Karl Knechtel Aug 01 '22 at 20:25
8 Answers
Would this work for your situation?
>>> s = '12abcd405'
>>> result = ''.join([i for i in s if not i.isdigit()])
>>> result
'abcd'
This makes use of a list comprehension, and what is happening here is similar to this structure:
no_digits = []
# Iterate through the string, adding non-numbers to the no_digits list
for i in s:
if not i.isdigit():
no_digits.append(i)
# Now join all elements of the list with '',
# which puts all of the characters together.
result = ''.join(no_digits)
As @AshwiniChaudhary and @KirkStrauser point out, you actually do not need to use the brackets in the one-liner, making the piece inside the parentheses a generator expression (more efficient than a list comprehension). Even if this doesn't fit the requirements for your assignment, it is something you should read about eventually :) :
>>> s = '12abcd405'
>>> result = ''.join(i for i in s if not i.isdigit())
>>> result
'abcd'

- 36,383
- 7
- 80
- 84
-
@SeanJohnson Awesome! I'm sure I learned that from somebody else on this site, so the cycle is complete :) – RocketDonkey Oct 12 '12 at 03:36
-
1
-
4In Python 2.7 and above, you don't need the brackets around the list comprehension. You can leave them out and it becomes a generator expression. – Kirk Strauser Oct 12 '12 at 03:38
-
@RocketDonkey add some explanation too, just seeing the code won't help the OP I guess. – Ashwini Chaudhary Oct 12 '12 at 03:44
-
@AshwiniChaudhary Good point - added (put the list comprehension version first to make the for-loop comparison a bit easier to decipher). – RocketDonkey Oct 12 '12 at 03:55
-
Jon Clements answer below using `s.translate` is about 10 times faster than the list comprehension (tested with Python 2.7). Just a heads up to anyone reading this later. – Patrick Oct 19 '16 at 10:27
And, just to throw it in the mix, is the oft-forgotten str.translate
which will work a lot faster than looping/regular expressions:
For Python 2:
from string import digits
s = 'abc123def456ghi789zero0'
res = s.translate(None, digits)
# 'abcdefghizero'
For Python 3:
from string import digits
s = 'abc123def456ghi789zero0'
remove_digits = str.maketrans('', '', digits)
res = s.translate(remove_digits)
# 'abcdefghizero'

- 138,671
- 33
- 247
- 280
-
24This approach won't work in Python3. Do instead: `'abc123def456ghi789zero0'.translate({ord(k): None for k in digits})` – valignatev Feb 24 '16 at 14:23
-
4
-
Not sure if your teacher allows you to use filters but...
"".join(filter(lambda x: x.isalpha(), "a1a2a3s3d4f5fg6h"))
returns-
'aaasdffgh'
Much more efficient than looping...
Example:
for i in range(10):
a.replace(str(i),'')

- 161
- 9

- 670
- 4
- 13
-
11
-
You can get a sting back by using `"".join(filter(lambda x: x.isalpha(), "a1a2a3s3d4f5fg6h"))`. That's an empty string in the beginning. – rodrigolece Jun 15 '22 at 17:26
-
Or better: "".join(filter(lambda ch: not ch.isdigit(), "a1a2a3s3d4f5fg6h")) --- so not isdigit is better suits the question. (I can't edit the answer :-( There are too many "edit is awaiting approval" message in the last half year.) – Arpad Horvath -- Слава Україні May 24 '23 at 10:12
Just a few (others have suggested some of these)
Method 1:
''.join(i for i in myStr if not i.isdigit())
Method 2:
def removeDigits(s):
answer = []
for char in s:
if not char.isdigit():
answer.append(char)
return ''.join(answer)
Method 3:
''.join(filter(lambda x: not x.isdigit(), mystr))
Method 4:
nums = set(map(int, range(10)))
''.join(i for i in mystr if i not in nums)
Method 5:
''.join(i for i in mystr if ord(i) not in range(48, 58))

- 110,290
- 27
- 149
- 241
What about this:
out_string = filter(lambda c: not c.isdigit(), in_string)

- 786
- 2
- 7
- 19
-
8
-
1@TitanFighter You can coerce the generator into a list object by wrapping that returned object from filter into list(filter(...)) – ahlusar1989 Jun 30 '19 at 19:10
Say st is your unformatted string, then run
st_nodigits=''.join(i for i in st if i.isalpha())
as mentioned above. But my guess that you need something very simple so say s is your string and st_res is a string without digits, then here is your code
l = ['0','1','2','3','4','5','6','7','8','9']
st_res=""
for ch in s:
if ch not in l:
st_res+=ch

- 1,329
- 1
- 8
- 9
I'd love to use regex to accomplish this, but since you can only use lists, loops, functions, etc..
here's what I came up with:
stringWithNumbers="I have 10 bananas for my 5 monkeys!"
stringWithoutNumbers=''.join(c if c not in map(str,range(0,10)) else "" for c in stringWithNumbers)
print(stringWithoutNumbers) #I have bananas for my monkeys!

- 5,567
- 2
- 17
- 22
If i understand your question right, one way to do is break down the string in chars and then check each char in that string using a loop whether it's a string or a number and then if string save it in a variable and then once the loop is finished, display that to the user

- 4,604
- 6
- 33
- 72
-
A for-loop automatically iterates through every character of a string, so no need of breaking the string into chars. – Ashwini Chaudhary Oct 12 '12 at 03:42