4
Contributors
3
Replies
4
Views
7 Years
Discussion Span
Last Post by jice
0

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

0

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

Edited by woooee: n/a

0

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

Edited by jice: n/a

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.