zoukankan      html  css  js  c++  java
  • Python String startswith() Method

    一,摘自官方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()相当于解冻一个元组。可以根据需要定义

  • 相关阅读:
    系统调用简单总结
    系统调用原理详解
    总结:c 语言与Linux操作系统的关系
    poj3171 Cleaning Shifts
    洛谷P1032 字串变换
    poj3662 Telephone Lines
    洛谷P1073 最优贸易
    Uva1330/poj1964 City Game
    poj2559/SP1805 Largest Rectangle in a Histogram
    洛谷 P1196 [NOI2002]银河英雄传说
  • 原文地址:https://www.cnblogs.com/sen-c7/p/10880610.html
Copyright © 2011-2022 走看看