user2891763
user2891763

Reputation: 423

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"

Upvotes: 3

Views: 19839

Answers (5)

Seymur Kazımov
Seymur Kazımov

Reputation: 11

a='a345g5'



for i in a:
    if int(i.isnumeric()):
        print(i,end=' ')

Upvotes: 1

Marlon Reugebrink
Marlon Reugebrink

Reputation: 1

sentence = "Hu765adjH665Sdjda"

for number in sentence:
    if number in "0123456789":
        print(number)

Upvotes: 0

dansalmo
dansalmo

Reputation: 11696

>>> s = "Hu765adjH665Sdjda"
>>> ''.join(c for c in s if c in '0123456789')
'765665'

Upvotes: 2

edi_allen
edi_allen

Reputation: 1872

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

Upvotes: 4

e271p314
e271p314

Reputation: 4039

Try filter

>>> str='1qaz2wsx3edc4rfv5tgb6yhn7ujm8ik9ol'
>>> print str
1qaz2wsx3edc4rfv5tgb6yhn7ujm8ik9ol
>>> filter(lambda x:x>='0' and x<='9', str)
'123456789'

Upvotes: 0

Related Questions