[Tutor] finding digit in string

Prasad, Ramit ramit.prasad at jpmorgan.com
Mon Oct 8 22:11:38 CEST 2012


Mark Lawrence wrote:
> On 08/10/2012 17:43, Benjamin Fishbein wrote:
> > I figured out a solution for the question I asked on here.
> > To find the next digit (0-9) in a string, I use:
> > text.find("0" or "1" or "2", etc.......)
> > But is there a more elegant way to do this? The way I found uses a lot of typing.
> >
> 
> How about something like:-
> 
> for ch in text:
>      if ch.isdigit():
>          doSomething(ch)
> 
> or:-
> 
> for ch in text:
>      if '0' <= ch <= '9':
>          doSomething(ch)

I am not sure that will work very well with Unicode numbers. I would 
assume (you know what they say about assuming) that str.isdigit() 
works better with international characters/numbers.

>>> '1'.isdigit()
True
>>> '23'.isdigit()
True
>>> '23a'.isdigit()
False

for ch in text:
    if ch.isdigit():
        # do something

> 
> 
> If you want to use the offset for any reason use enumerate:-
> 
> for i, ch in enumerate(text):
>      etc.
> 
> --
> Cheers.
> 
> Mark Lawrence.

This email is confidential and subject to important disclaimers and
conditions including on offers for the purchase or sale of
securities, accuracy and completeness of information, viruses,
confidentiality, legal privilege, and legal entity disclaimers,
available at http://www.jpmorgan.com/pages/disclosures/email.  


More information about the Tutor mailing list