zoukankan      html  css  js  c++  java
  • python字符串常用内置方法

    python字符串常用内置方法

    定义:
    字符串是一个有序的字符的集合,用与存储和表示基本的文本信息。
    python中引号中间包含的就是字符串。

    # s1='hello world'
    # s2="hello world"
    # s3="""hello world"""
    # s3='''hello world'''  
    

    补充: 

    • 字符串的单引号和双引号都无法取消特殊字符的含义,如果想让引号内所有字符均取消特殊意义,在引号前面加r,如name=r'l hf'

    • unicode字符串与r连用必需在r前面,如name=ur'l hf'

        #>>> print('a
      b')  
        a   
        b  
        #>>> print(r'a
      b')  
        a
      b  
      

    字符串连接

    示例:
    >>> x = 'hello world!'
    >>> x = x[:6] + 'tom'
    >>> x
    'hello tom'

    内置函数len()

    len() 方法返回对象(字符串、列表、元组等)长度或项目个数。
    语法:
    len(s)
    s-----对象

    >>> str ='hello world'
    >>> len(str)
    11
    >>> L = [1,2,3,4,5]
    >>> len(L)
    5
    >>> 
    

    strip()

    strip英文翻译:脱掉,剥夺
    strip()默认移除字符串两边的空白。只是返回处理后的副本,原来的值不变。

    >>> x='    tom     '
    >>> x
    '    tom     '
    >>> x.strip()
    'tom'
    >>> 
    

    也可以自己指定要去除的目标:

    >>> x='ssssstomsssss'
    >>> x.strip('s')
    'tom'
    >>> x='#######tom####'
    >>> x.strip('#')
    'tom'
    

    同类的还有lstrip(),rstrip()

    >>> x='#######tom####'
    >>> x.lstrip('#')
    'tom####'
    >>> x.rstrip('#')
    '#######tom'
    >>> 
    

    capitalize()

    capitalize()返回首字母大写的副本,不改变原来的值:

    >>> x='hello,world'
    >>> x.capitalize()
    'Hello,world'
    

    title()

    title()返回标题样式的副本(单词首字母大写),不改变原来的值:

    >>> x='hello,world'
    >>> x.title()
    'Hello,World'
    

    upper()

    upper()返回所有字母大写的副本,不改变原来的值:

    >>> x='hello,world'
    >>> x.upper
    'HELLO,WORLD'
    

    lower()

    lower()返回所有字母小写的副本,不改变原来的值:

    >>> x='Hello,World'
    >>> x.lower()
    'hello,world'
    >>> 
    

    center()

    center()返回一个原字符串居中,并使用空格填充至长度 width 的新字符串。默认填充字符为空格。居中显示
    语法:
    str.center(width[,fillchar])
    width------字符串的总宽度
    fillchar-----填充字符

    >>> x='hello'
    >>> x.center(15,'#')
    '#####hello#####'
    >>>
    

    count()

    count()方法用于统计字符串里某个字符出现的次数。可选参数为在字符串搜索的开始与结束位置。空格也是字符。
    语法:
    str.count(sub,start,end)
    sub-----搜索的子字符串
    start----字符串开始搜索的位置,默认为第一个字符,第一个字符索引值为0
    end-----字符串中结束搜索的位置。默认为字符串的最后一个位置。

    >>> x='hel lo love'
    >>> x.count(' ')
    2
    >>> x.count('l',0,4)
    1
    

    endswith()

    endswith() 方法用于判断字符串是否以指定后缀结尾,如果以指定后缀结尾返回True,否则返回False。可选参数"start"与"end"为检索字符串的开始与结束位置。
    语法:
    str.endswith(suffix,start,end)
    suffix----该参数可以是一个字符串或者是一个元素
    start----字符串开始的位置
    end------字符中结束的位置

    >>> x='/bin/nologin'
    >>> x.endswith('n')
    True
    >>> x.endswith('nologin')
    True
    >>> 
    

    startswith()

    startswith() 方法用于检查字符串是否是以指定子字符串开头,如果是则返回 True,否则返回 False。如果参数 beg 和 end 指定值,则在指定范围内检查。
    语法:
    str.startwith(str,strbegin,strend)
    str-----检测的字符串。
    strbegin----可选参数用于设置字符串检测的起始位置。
    strend----可选参数用于设置字符串检测的结束位置

    >>> x.startswith('/')
    True
    >>> x.startswith('/bin')
    True
    >>> 
    

    find()

    find() 方法检测字符串中是否包含子字符串 str ,如果指定 beg(开始) 和 end(结束) 范围,则检查是否包含在指定范围内,如果包含子字符串返回开始的索引值,否则返回-1。(没找到就返回-1)
    语法:
    str.find(str,begin,end)
    str-----指定检索的字符串
    begin----开始索引,默认为0
    end-----结束索引,默认为字符串的长度

    >>> x='/etc/sshd/ssh.conf'
    >>> x.find('/')
    0
    >>> x.find('/',1,4)
    -1
    >>> x.find('.conf')
    13
    >>>
    >>>> x.find('.cont')
    -1
    >>> 
    

    format()

    format()和%格式化功能一样,基本语法是通过 {} 和:来代替以前的%。format函数可以接受不限个参数,位置可以不按顺序。
    示例:

    >>> msg='Nname:{},age:{},sex:{}'
    >>> print(msg.format('tom',18,'male'))
    Nname:tom,age:18,sex:male
    
    >>> msg='Nname:{x},age:{y},sex:{z}'
    >>> print (msg.format(x='tom',y=18,z='male'))
    Nname:tom,age:18,sex:male
    
    >>> url='https://movie.douban.com/top250?start={page}&filter=&type='
    >>> print(url.format(page=50))
    https://movie.douban.com/top250?start=50&filter=&type=
    >>> 
    

    字符串切片

    str[索引初始:索引结束:索引步长]

    >>> print (x[0])
    h
    >>> print (x[0:3])
    hel
    >>> print (x[0:5:2])
    hlo
    >>> print (x[::-1])
    dlrow olleh
    >>> 
    >>> print (x[:-1])
    hello worl
    >>> print (x[1:])
    ello world
    >>> 
    

    简而言之,分片操作的实现需要提供两个索引作为边界,第一个索引元素包含在分片内,第二个则不包含在分片内。
    对于分片还可以使用更大的步长,步长为负数的时候,从尾部开始取数据

    isdigit()

    digit英文解释:数字
    isdigit()判断字符串内是否全是数字。如果字符串只包含数字则返回 True 否则返回 False。

    >>> x='12345'
    >>> x.isdigit()
    True
    >>> x='3.1415'
    >>> x.isdigit()
    False
    >>> 
    

    isalpha()

    isalpha() 方法检测字符串是否只由字母组成。如果字符串至少有一个字符并且所有字符都是字母则返回 True,否则返回 False

     >>> x='adswqeq     '
    >>> x.isalpha()
    False
    >>> x='a'
    >>> x.isalpha()
    True
    >>> 
    

    index()

    index() 方法检测字符串中是否包含子字符串 str ,如果指定 beg(开始) 和 end(结束) 范围,则检查是否包含在指定范围内,该方法与 python find()方法一样,只不过如果str不在 string中会报一个异常。

    >>> x='/etc/sshd/ssh.conf'
    >>> x.index('/')
    0
    >>> x.index('/',1,4)
    Traceback (most recent call last):
    File "<pyshell#90>", line 1, in <module>
    x.index('/',1,4)
    ValueError: substring not found
    >>> x.index('.conf')
    13
    >>> x.index('.cont')
    Traceback (most recent call last):
    File "<pyshell#92>", line 1, in <module>
    x.index('.cont')
    ValueError: substring not found
    >>> 
    

    replace()

    replace() 方法把字符串中的 old(旧字符串) 替换成 new(新字符串),如果指定第三个参数max,则替换不超过 max 次。
    语法:
    str.replace(old,new,max)
    old----将被替换的子字符串
    new----新字符串,用于替换old子字符串
    max----指定替换次数

    >>> x='this is test'
    >>> x.replace('is','are')
    'thare are test'
    >>> x.replace('is','are',1)
    'thare is test'
    >>> x.replace('is','are',2)
    'thare are test'
    >>> x.replace('is','are',3)
    'thare are test'
    >>> 
    

    split()

    split()通过指定分隔符对字符串进行切片,如果参数num 有指定值,则仅分隔 num 个子字符串
    语法:
    str.split('分隔符',分隔次数)
    分隔符默认为所有的空字符,包括空格、换行( )、制表符( )等。

    >>> x='root:x:0:0::/root:/bin/bash'
    >>> x.split()
    ['root:x:0:0::/root:/bin/bash']
    >>> x.split(':')
    ['root', 'x', '0', '0', '', '/root', '/bin/bash']
    >>> x.split(':',2)
    ['root', 'x', '0:0::/root:/bin/bash']
    >>> x.split(':',3)
    ['root', 'x', '0', '0::/root:/bin/bash']
    >>> 
    

    isspace()

    isspace() 方法检测字符串是否只由空格组成。
    语法:
    str.isspace()
    如果字符串中只包含空格,则返回 True,否则返回 False.和将一段空字符串使用strip处理后判断是否等于''一样。

    >>> x = '        '
    >>> x.isspace()
    True
    >>> x.strip() == ''
    True
    >>> 
    

    swapcase()

    swapcase() 方法用于对字符串的大小写字母进行转换。
    语法
    str.swapcase()
    返回大小写字母转换后生成的新字符串。

    >>> x = '''it's good!'''
    >>> x.swapcase()
    "IT'S GOOD!"
    >>> x = 'Ab'
    >>> x.swapcase()
    'aB'
    >>> 
    

    ljust()和rjust()

    ljust() 方法返回一个原字符串左对齐,并使用空格填充至指定长度的新字符串。如果指定的长度小于原字符串的长度则返回原字符串。
    语法:
    str.ljust(width,fillchar)
    width-----指定字符串长度
    fillchar----填充字符,默认为空格

    >>> x = 'tom'
    >>> x.ljust(10,'#')
    'tom#######'
    

    rjust() 方法返回一个原字符串右对齐,并使用空格填充至长度 width 的新字符串。如果指定的长度小于字符串的长度则返回原字符串。
    示例:

    >>> x = 'tom'
    >>> x.rjust(10,'#')
    '#######tom'
    >>> 
    
    序号方法及描述
    1

    capitalize()
    将字符串的第一个字符转换为大写

    2

    center(width, fillchar)


    返回一个指定的宽度 width 居中的字符串,fillchar 为填充的字符,默认为空格。
    3

    count(str, beg= 0,end=len(string))


    返回 str 在 string 里面出现的次数,如果 beg 或者 end 指定则返回指定范围内 str 出现的次数
    4

    bytes.decode(encoding="utf-8", errors="strict")


    Python3 中没有 decode 方法,但我们可以使用 bytes 对象的 decode() 方法来解码给定的 bytes 对象,这个 bytes 对象可以由 str.encode() 来编码返回。
    5

    encode(encoding='UTF-8',errors='strict')


    以 encoding 指定的编码格式编码字符串,如果出错默认报一个ValueError 的异常,除非 errors 指定的是'ignore'或者'replace'
    6

    endswith(suffix, beg=0, end=len(string))
    检查字符串是否以 obj 结束,如果beg 或者 end 指定则检查指定的范围内是否以 obj 结束,如果是,返回 True,否则返回 False.

    7

    expandtabs(tabsize=8)


    把字符串 string 中的 tab 符号转为空格,tab 符号默认的空格数是 8 。
    8

    find(str, beg=0 end=len(string))


    检测 str 是否包含在字符串中 中,如果 beg 和 end 指定范围,则检查是否包含在指定范围内,如果是返回开始的索引值,否则返回-1
    9

    index(str, beg=0, end=len(string))


    跟find()方法一样,只不过如果str不在字符串中会报一个异常.
    10

    isalnum()


    如果字符串至少有一个字符并且所有字符都是字母或数字则返 回 True,否则返回 False
    11

    isalpha()


    如果字符串至少有一个字符并且所有字符都是字母则返回 True, 否则返回 False
    12

    isdigit()


    如果字符串只包含数字则返回 True 否则返回 False..
    13

    islower()


    如果字符串中包含至少一个区分大小写的字符,并且所有这些(区分大小写的)字符都是小写,则返回 True,否则返回 False
    14

    isnumeric()


    如果字符串中只包含数字字符,则返回 True,否则返回 False
    15

    isspace()


    如果字符串中只包含空格,则返回 True,否则返回 False.
    16

    istitle()


    如果字符串是标题化的(见 title())则返回 True,否则返回 False
    17

    isupper()


    如果字符串中包含至少一个区分大小写的字符,并且所有这些(区分大小写的)字符都是大写,则返回 True,否则返回 False
    18

    join(seq)


    以指定字符串作为分隔符,将 seq 中所有的元素(的字符串表示)合并为一个新的字符串
    19

    len(string)


    返回字符串长度
    20

    ljust(width[, fillchar])


    返回一个原字符串左对齐,并使用 fillchar 填充至长度 width 的新字符串,fillchar 默认为空格。
    21

    lower()


    转换字符串中所有大写字符为小写.
    22

    lstrip()


    截掉字符串左边的空格
    23

    maketrans()


    创建字符映射的转换表,对于接受两个参数的最简单的调用方式,第一个参数是字符串,表示需要转换的字符,第二个参数也是字符串表示转换的目标。
    24

    max(str)


    返回字符串 str 中最大的字母。
    25

    min(str)


    返回字符串 str 中最小的字母。
    26

    replace(old, new [, max])


    把 将字符串中的 str1 替换成 str2,如果 max 指定,则替换不超过 max 次。
    27

    rfind(str, beg=0,end=len(string))


    类似于 find()函数,不过是从右边开始查找.
    28

    rindex( str, beg=0, end=len(string))


    类似于 index(),不过是从右边开始.
    29

    rjust(width,[, fillchar])


    返回一个原字符串右对齐,并使用fillchar(默认空格)填充至长度 width 的新字符串
    30

    rstrip()


    删除字符串字符串末尾的空格.
    31

    split(str="", num=string.count(str))


    num=string.count(str)) 以 str 为分隔符截取字符串,如果 num 有指定值,则仅截取 num 个子字符串
    32

    splitlines([keepends])


    按照行(' ', ' ', ')分隔,返回一个包含各行作为元素的列表,如果参数 keepends 为 False,不包含换行符,如果为 True,则保留换行符。
    33

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


    检查字符串是否是以 obj 开头,是则返回 True,否则返回 False。如果beg 和 end 指定值,则在指定范围内检查。
    34

    strip([chars])


    在字符串上执行 lstrip()和 rstrip()
    35

    swapcase()


    将字符串中大写转换为小写,小写转换为大写
    36

    title()


    返回"标题化"的字符串,就是说所有单词都是以大写开始,其余字母均为小写(见 istitle())
    37

    translate(table, deletechars="")


    根据 str 给出的表(包含 256 个字符)转换 string 的字符, 要过滤掉的字符放到 deletechars 参数中
    38

    upper()


    转换字符串中的小写字母为大写
    39

    zfill (width)


    返回长度为 width 的字符串,原字符串右对齐,前面填充0
    40

    isdecimal()


    检查字符串是否只包含十进制字符,如果是返回 true,否则返回 false。
  • 相关阅读:
    pycharm中Terminal中运行用例
    python pandas模块简单使用(读取excel为例)
    pytest框架,使用print在控制台输入
    CentOS7配置python3教程
    linux 添加与修改用户归属组
    python 连接oracle基础环境配置方法
    robot framework 接口post请求需要加headers
    unittest中的parameterized参数化
    json格式
    Django_URL
  • 原文地址:https://www.cnblogs.com/liao-lin/p/6958908.html
Copyright © 2011-2022 走看看