python string字符串函数

python partition()函数用于根据指定的分隔符(sep)将字符串进行分割。从字符串左边开始索引分隔符sep,索引到则停止索引。

语法

str.partition(sep) 

    语法

    • sep:指定的分隔符。
      • 如果字符串包含指定的分隔符sep,则返回一个三元元组,第一个为分隔符sep左边的子字符串,第二个为分隔符sep本身,第三个为分隔符sep右边的子字符串。
      • 如果字符串不包含指定的分隔符sep,仍然返回一个三元元组,第一个元素为字符串本身,第二第三个元素为空字符串

    返回值

     (head, sep, tail)  返回一个三元元组,head:分隔符sep前的字符串,sep:分隔符本身,tail:分隔符sep后的字符串。

    程序示例

    #!/usr/bin/python
    # coding=utf-8
    str = "https://www.baidu.com/"
    print(str.partition("://")) #字符串str中存在sep"://"
    print(str.partition(","))  #字符串str中不存在sep",",返回了两个空字符串。
    print(str.partition("."))  #字符串str中存在两个"." 但索引到www后的"."  停止索引。
    print(type(str.partition("://"))) #返回的是tuple类型, 即元组类型 
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    程序运行结果:

    ('https', '://', 'www.baidu.com/')
    ('https://www.baidu.com/', '', '')
    ('https://www', '.', 'baidu.com/')
    <class 'tuple'>