简体   繁体   中英

Print only the numbers in the string in python

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)

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

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM