Python3 如何检查字符串是否是以指定子字符串开头或结尾

Python3 中提供了两个字符串的内置方法 str.startswith()str.endswith()

1. 用于检查字符串是否是以指定子字符串开头,如果是则返回 True,否则返回 False。如果参数 begend 指定值,则在指定范围内检查

str.startswith(substr, beg=0,end=len(string))

  • str:被检测的字符串

  • substr:指定的子字符串

  • strbeg:可选参数用于设置字符串检测的起始位置

  • strend:可选参数用于设置字符串检测的结束位置

      #!/usr/bin/env python3
      # -*- coding: UTF-8 -*-
      
      str = "this is string example....wow!!!"
      
      # 字符串是否以 this 开头
      print (str.startswith('this'))
      # 从第8个字符开始的字符串是否以 string 开头
      print (str.startswith('string', 8))
      # 从第2个字符开始到第4个字符结束的字符串是否以 this 开头
      print (str.startswith('this', 2, 4))
    

    运行结果:

      Geek-Mac:Downloads zhangyi$ python3 Nice.py 
      True
      True
      False
    

2. 用于判断字符串是否以指定后缀结尾,如果以指定后缀结尾返回 True,否则返回 False。可选参数 startend 为检索字符串的开始与结束位置

str.endswith(suffix[, start[, end]])

  • suffix:该参数可以是一个字符串或者是一个元素

  • start:字符串中的开始位置

  • end:字符中结束位置

      # -*- coding: UTF-8 -*-
      
      str = "this is string example....wow!!!"
      
      # 字符串是否以 wow 结尾
      print (str.endswith('wow'))
      # 字符串是否以 !!! 结尾
      print (str.endswith('!!!'))
      # 从第6个字符开始,是否以 is 结尾
      print (str.endswith('is', 6))
      # 从第1个字符开始到第7个字符结束的字符串是否以 is 结尾
      print (str.endswith('is', 1, 7))
    

    运行结果:

      Geek-Mac:Downloads zhangyi$ python3 Nice.py 
      False
      True
      False
      True
    

版权声明:本文为yilovexing原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。