简体   繁体   中英

Python regex to determine whether a character is numeric, alphanumeric or in a specified string

I am unsure as to how one would use a Python regex to determine whether a character is numeric, alphanumeric or in a specified string.

Something like (fake code warning):

if 'a' in re.['A-Z']:
   print "Alpha"

if '.' in re.['.,;']:
   print "Punctiation"

Use str.isalpha() method:

>>> 'a'.isalpha()
True

For testing single character for punctuation or alphanumeric, you can use constants pre-defined in string module:

>>> '.' in string.punctuation:
True

You can use the match function from module re :

import re

x = 'a'
if re.match('[a-zA-Z]', x):
    print "Alpha"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM