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"
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).
>>> s = "Hu765adjH665Sdjda"
>>> ''.join(c for c in s if c in '0123456789')
'765665'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With