如何判断字符串以数字或指定正则表达式开头?Python提供了多种方式,以下是常用的两种方案:
1、str.isdigit()方法
Python提供了多种字符串方法,例如:isupper()
判断字符串是否是大写、isdigit()
判断字符串是否是数字等
以下是一个示例:
python
s1 = "10.-Not All"
s2 = "-1.-Not All"
print(s1[0].isdigit()) # True
print(s1[0:2].isdigit()) # True
如果是s2
这种字符串,要判断它是否以-
和数字开头,该如何判断?
2、re.match()方法
对于s2
这样的字符串,我们可以考虑使用正则表达式的方式。Python的re
模块提供了这种实现:
python
re.match(pattern,string,flags=0)
该方法可用于判断目标字符串是否以匹配的正则表达式开头,如果匹配,则返回match
对象,否则返回None
以下是一个示例:
python
print(re.match('\\d', s1).group(0)) # 1
print(True if re.match('\\d', s1) else False) # True
print(True if re.match('-\\d', s2) else False) # True