码迷,mamicode.com
首页 > 编程语言 > 详细

Python String startswith() Method

时间:2019-05-17 13:50:34      阅读:135      评论:0      收藏:0      [点我收藏+]

标签:types.h   not   相互   option   类型   utils   nal   指定   数据   

一,摘自官方API  https://docs.python.org/3/library/stdtypes.html#methods

str.startswith(prefix[, start[, end]])

Return True if string starts with the prefix, otherwise return Falseprefix can also be a tuple of prefixes to look for. With optional start, test string beginning at that position. With optional end, stop comparing string at that position.

二,摘自 https://www.runoob.com/python/att-string-startswith.html

描述:

Python startswith() 方法用于检查字符串是否是以指定子字符串开头,如果是则返回 True,否则返回 False。如果参数 beg 和 end 指定值,则在指定范围内检查。

startswith()方法语法:

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

参数:

  • str -- 检测的字符串。
  • strbeg -- 可选参数用于设置字符串检测的起始位置。
  • strend -- 可选参数用于设置字符串检测的结束位置。

返回值:

如果检测到字符串则返回True,否则返回False。

实例:

#!/usr/bin/python

str = "this is string example....wow!!!";
print str.startswith( this );
print str.startswith( is, 2, 4 );
print str.startswith( this, 2, 4 );

结果:

True
True
False

 

拓展:

有多个指定开头的字符串需要判断时,可以给prefix参数传一个元组

示例:

str1 = a-123
str2 = b-123
str3 = c-123
str4 = d-123

pre_list = [a, b]
pre_tuple = (a, b)
print(str1.startswith(tuple(pre_list)))
print(str2.startswith(pre_tuple))
print(str3.startswith(pre_tuple))
print(str4.startswith(tuple(pre_list)))

结果:

True
True
False
False

 

备注:tuple类型和list类型可以互转~~

元组与列表的区别在于:元组比列表的运算速度快,而且元组的数据比较安全。元组是不可改变的,为了保护其内容不被外部接口修改,不具有 append,extend,remove,pop,index这些功能;而列表是可更改的。所有有些时候我们需要两者相互转换,tuple()相当于冻结一个列表,而list()相当于解冻一个元组。可以根据需要定义

 

Python String startswith() Method

标签:types.h   not   相互   option   类型   utils   nal   指定   数据   

原文地址:https://www.cnblogs.com/sen-c7/p/10880610.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!