How do i print only a string of numbers in python?

Hello I am fairly new at programming and python and I have a question.

How would I go about printing or returning only numbers from a string

For example:

"Hu765adjH665Sdjda"

output:

"765665"

asked Oct 20, 2013 at 23:15

You can use re.sub to remove any character that is not a number.

import re

string = "Hu765adjH665Sdjda"
string = re.sub['[^0-9]', '', string]
print string
#'765665'

re.sub scan the string from left to right. everytime it finds a character that is not a number it replaces it for the empty string [which is the same as removing it for all practical purpose].

answered Oct 20, 2013 at 23:25

edi_allenedi_allen

1,7581 gold badge10 silver badges8 bronze badges

6

>>> s = "Hu765adjH665Sdjda"
>>> ''.join[c for c in s if c in '0123456789']
'765665'

answered Oct 20, 2013 at 23:25

dansalmodansalmo

11.1k5 gold badges55 silver badges51 bronze badges

a='a345g5'



for i in a:
    if int[i.isnumeric[]]:
        print[i,end=' ']

Sach

8548 silver badges20 bronze badges

answered Jun 22 at 22:00

Try filter

>>> str='1qaz2wsx3edc4rfv5tgb6yhn7ujm8ik9ol'
>>> print str
1qaz2wsx3edc4rfv5tgb6yhn7ujm8ik9ol
>>> filter[lambda x:x>='0' and x=48 && sarr[i]/1

Chủ Đề