Home > Mobile >  Print only the numbers in the string in python
Print only the numbers in the string in python

Time:11-17

I need to print only the numbers in the string and I don't know how to do it I mean for example mystring="ab543", How to get 543 as int?

I tried something like that

my_string="ab543"
numlst=["0","1","2","3","4","5","6","7","8","9"]
countfinish=0
whichnum=""
for charr in my_string:
    for num in numlst:
        if num==charr:
            whichnum=whichnum str(num)
    break
    countfinish=countfinish int(whichnum)
print(countfinish)

CodePudding user response:

You can try:

>>> my_string="ab543"
>>> "".join([str(s) for s in my_string if s.isdigit()])
'543'
>>> int("".join([str(s) for s in my_string if s.isdigit()]))
543

You also can use filter :

>>> my_string="ab543"
>>> int(''.join(filter(str.isdigit, my_string)))
543

CodePudding user response:

You can use regular expressions:

import re
pattern = "\d [.]?\d*"
re.findall(pattern, my_string)

The pattern used here should give you also float numbers. For example if my_string="ab543ab2392alsow435.32", then you get the following output:

['543', '2392', '435.32']

Afterwards you can use the int() function to convert them to ints.

CodePudding user response:

I am not sure if that's the answer you were looking for, but you could try to use .isdigit() to check if a character is a number.

my_string="ab543"
numbers = []
for i in my_string:
    if (i.isdigit()):
        numbers.append(i)
final = "".join(numbers)
print(final) # prints 543
print(int(final)) # prints 543
  • Related