Python string.endswith()用于检查特定文本模式(例如域名扩展等)的字符串结尾。
检查字符串结尾的一种简单方法是使用String.endswith()
。
example1.py
>>> url = 'http://www.leftso.com'
>>> url.endswith('.com')
True #输出
>>> url.endswith('.net')
false #输出
如果您需要检查多个选择,只需提供一组元串即可endswith()
。
example2.py
>>> domains = ["example.io", "example.com", "example.net", "example.org"]
>>> [name for name in domains if name.endswith(('.com', '.org')) ]
['example.com', 'example.org'] #输出
>>> any( name.endswith('.net') for name in domains )
True #输出
要使用endswith()
,实际上需要元组作为输入。如果您碰巧在列表或集合中指定了选项,请确保首先使用它们进行转换tuple()
。
例如:
$title(example3.py)
>>> choices = ['.com', '.io', '.net']
>>> url = 'http://www.leftso.com'
>>> url.endswith(choices) #ERROR !! TypeError: endswith first arg must be str, unicode, or tuple, not list
>>> url.endswith( tuple(choices) ) #Correct
True #输出
https://www.leftso.com/article/730.html