How To Check For [a-z] In String?

Peter Abel PeterAbel at gmx.net
Thu Oct 2 15:23:06 EDT 2003


Hank Kingwood <hank at bogusaddress.xyz> wrote in message news:<e0Xeb.2$gQ.133058630 at newssvr12.news.prodigy.com>...
> Also, how would I check if [a-z] is not in a string?
> 
> Thanks again,
> Hank
> 
> Hank Kingwood wrote:
> > This is probably an easy question, but I can't find a function (maybe my 
> > syntax is off...) to search for [a-z] in a string.  If someone would 
> > help out, I'd appreciate it!
> > 
> > Also, how would you recommend searching for the following in the same 
> > string:
> >   [a-z]
> >   [A-Z]
> >   [0-9]
> >   -
> > 
> > My approach would be to perform four separte checks, but I'm thinking 
> > there might be some cool approach that would use a dictionary or array. 
> >  Ideas?
> > 
> > Thanks,
> > Hank
> >

Use regular expressions.

>>> import re
>>> any_string="find a-z, A-Z and 0-9, **+#-#?** no specials"
>>> re_search=re.compile(r'(\w+)')
>>> re_search.findall(any_string)
['find', 'a', 'z', 'A', 'Z', 'and', '0', '9', 'no', 'specials']
>>> # Or
>>> re_search=re.compile(r'(\w)')
>>> re_search.findall(any_string)
['f', 'i', 'n', 'd', 'a', 'z', 'A', 'Z', 'a', 'n', 'd', '0', '9', 'n',
'o', 's', 'p', 'e', 'c', 'i', 'a', 'l', 's']
>>> 

The **\w** means a-z plus A-Z plus 0-9 plus _.
If you doen't want to get the underline you have to define:
[a-zA-Z0-9] instead.

For more information read the docu for the re-module.

Regards
Peter




More information about the Python-list mailing list