Python string.startswith()方法用于检查特定文本模式(例如URL方案等)的字符串以什么开头。
用于检查字符串开头的简单python程序是使用String.startswith()
。
$title(example1.py)
>>> url = 'http://blog.xqlee.com'
>>> url.startswith('http:')
True #输出
>>> url.startswith('https:')
False #输出
如果您需要检查多个选择,只需向中提供一个字符串元组startswith()
。
$title(example2.py)
>>> fileNames=["张小三","李小四","王小五","张老六"]
>>> [name for name in fileNames if name.startswith(('张','李'))]
['张小三', '李小四', '张老六'] #输出
>>> any(name.startswith('张小') for name in fileNames)
True
要使用startswith()
,实际上需要元组作为输入。如果您碰巧在列表或集合中指定了选择,只需确保首先使用tuple()进行转换即可。
例如:
$title(example3.py)
>>> choices = ['https:', 'http:', 'ftp:']
>>> url = 'http://blog.xqlee.com'
>>> url.startswith(choices) #ERROR !! TypeError: startswith first arg must be str, unicode, or tuple, not list
>>> url.startswith( tuple(choices) ) #Correct
True #输出
http://blog.xqlee.com/article/729.html