加入收藏 | 设为首页 | 会员中心 | 我要投稿 北几岛 (https://www.beijidao.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

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

发布时间:2021-05-21 04:55:49 所属栏目:大数据 来源: https://blog.csdn.net/yilovex
导读:Python3 中提供了两个字符串的内置方法 str.startswith() 和 str.endswith() 1. 用于检查字符串是否是以指定子字符串开头,如果是则返回 True ,否则返回 False 。如果参数 beg 和 end 指定值,则在指定范围内检查 str.startswith(substr,beg=0,end=len(stri

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
    

(编辑:北几岛)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读