如何在Python中检查字符串是否以XYZ开头?

Python在String类中有一个startswith(string)方法。此方法接受要搜索的前缀字符串,并在字符串对象上调用。您可以通过以下方式调用此方法:

>>>'hello world'.startswith('hell')
True
>>>'hello world'.startswith('nope')
False

 还有另一种查找字符串是否以给定前缀结尾的方法。您可以使用re模块(正则表达式)中的re.search('^'+前缀,字符串)进行操作。正则表达式将^解释为行的开头,因此,如果要搜索前缀,则需要执行以下操作:

>>>import re
>>>bool(re.search('^hell', 'hello world'))
True
>>>bool(re.search('^nope', 'hello world'))
False