Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I print only integers/numbers from string

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"
like image 462
user2891763 Avatar asked Dec 14 '25 03:12

user2891763


2 Answers

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).

like image 166
edi_allen Avatar answered Dec 16 '25 13:12

edi_allen


>>> s = "Hu765adjH665Sdjda"
>>> ''.join(c for c in s if c in '0123456789')
'765665'
like image 43
dansalmo Avatar answered Dec 16 '25 13:12

dansalmo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!