How To Check For [a-z] In String?
Jay Dorsey
jay at jaydorsey.com
Thu Oct 2 11:15:54 EDT 2003
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?
Are you looking for the actual string [a-z] in a string, or are you
looking for the regular expression [a-z] (any one lowercase letter)
Actual string:
>>> import re
>>> regex = re.compile('\[a-z\]')
>>> regex.search('123123[a-z]adsfasfd').group()
'[a-z]'
Regex pattern:
>>> import re
>>> regex = re.compile('[a-z]')
>>> regex.search('123123123a123123b123123c').group()
'a'
>>> regex.findall('123123123a123123b123123c')
['a', 'b', 'c']
You could also do:
>>> import re
>>> regex = re.compile('[a-z]|[A-Z]')
>>> regex.findall('123a23423b13123c123123A123B123C')
['a', 'b', 'c', 'A', 'B', 'C']
There are probably other ways to do it with list comprehensions, but
does that help?
Jay
More information about the Python-list
mailing list