I am having a hard time identifying numbers in a text. Is there a way to recognize numbers?

Recommended Answers

All 3 Replies

I am having a hard time identifying numbers in a text. Is there a way to recognize numbers?

you can use isdigit

st = "abcd123"

for i in st :
       if st.isdigit() == True :
                 print i

use dir(st) to find out all functions associated with a string

Test your code. It doesn't print anything. Also, please use no more than 4 spaces for indents. Finally, it is bad practice to use "i", "l", or "o" as single letter variable names as they can look like numbers. There are at least 3 ways to solve the problem.

st = "abcd123"

for ch in st:
    if ch.isdigit():
        print ch 

print "----------------------------------------------"
for ch in st:
    if (ch  >= "0") and (ch <= "9"):
        print ch 

print "---------"
for ch in st:
    try:
        print int(ch)
    except:
        pass

a fourth :

import re
st = "abcd123"
rdigit=re.compile("\d")
print rdigit.findall(st)

Which can be onelined :

import re
print re.compile("\d").findall("abcd123")
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.