当前位置 博文首页 > python中str内置函数用法总结

    python中str内置函数用法总结

    作者:宋宋大人 时间:2021-02-17 09:08

    大家在使用python的过程中,应该在敲代码的时候经常遇到str内置函数,为了防止大家搞混,本文整理归纳了str内置函数。1字符串查找类:find、index;2、字符串判断类:islower、isalpha;3、内容判断类:tartswith、endswith;4、操作类函数:format、strip、join。

    1、字符串查找类:find、index

    find和index均是查找字符串中是否包含一个子串;

    二者的区别是index找不到字符串会报错,而find会返回-1;

    rfind、lfind是从左开始查找或从右开始查找。

    2、字符串判断类:islower、isalpha

    此类函数的特点是is开头

    isalpha:判断是不是字母,需要注意两点:

    此函数默认的前提是字符串中至少包含一个字符,若没有,则返回false

    汉字被认为是alpha,此函数不能区分英文字母和汉字,区分中英文请使用unicode码

    isdigit、isnumeric、isdecimal三个判断数字的函数

    islower判断是否是小写

    3、内容判断类

    startswith、endswith:是否以XXX开头或结尾

    4、操作类函数

    format:格式化函数

    strip:删除字符串两边的字符(默认空格),可指定字符,不是删除一个,而是从头开始符合条件的连续字符。

    rstrip、lstrip删除右边/左边的字符。

    join:对字符串进行拼接

    s1='$'
    s2='-'
    s3=' '
    ss=['Today','is','a','good','day']
    print(s1.join(ss))
    Today$is$a$good$day
    print(s2.join(ss))
    Today-is-a-good-day
    print(s3.join(ss))
    Today is a good day

    实例扩展:

    >>>s = 'RUNOOB'
    >>> str(s)
    'RUNOOB'
    >>> dict = {'runoob': 'runoob.com', 'google': 'google.com'};
    >>> str(dict)
    "{'google': 'google.com', 'runoob': 'runoob.com'}"
    >>>
    js