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.
我不确定如何使用Python正则表达式来确定字符是数字,字母数字还是指定的字符串。
Something like (fake code warning):
像(假码警告):
if 'a' in re.['A-Z']:
print "Alpha"
if '.' in re.['.,;']:
print "Punctiation"
2 个解决方案
#1
#2
2
Use str.isalpha()
method:
使用str.isalpha()方法:
>>> 'a'.isalpha()
True
For testing single character for punctuation or alphanumeric, you can use constants pre-defined in string
module:
要测试标点符号或字母数字的单个字符,可以使用字符串模块中预定义的常量:
>>> '.' in string.punctuation:
True
#1
1
You can use the match
function from module re
:
您可以使用模块re中的匹配功能:
import re
x = 'a'
if re.match('[a-zA-Z]', x):
print "Alpha"
#2
2
Use str.isalpha()
method:
使用str.isalpha()方法:
>>> 'a'.isalpha()
True
For testing single character for punctuation or alphanumeric, you can use constants pre-defined in string
module:
要测试标点符号或字母数字的单个字符,可以使用字符串模块中预定义的常量:
>>> '.' in string.punctuation:
True