zoukankan      html  css  js  c++  java
  • python 字符串操作二 内建函数

    一、查看字符串的内建函数

    >>> dir(str)
    ['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__',
    '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__',
    '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__',
    '__str__', '__subclasshook__', 'capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format',
    'format_map', 'index', 'isalnum', 'isalpha', 'isdecimal', 'isdigit', 'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace',
    'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition',
    'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']
    In [1]: a = '123'
    
    In [2]: a.
    a.capitalize    a.endswith      a.index         a.isidentifier  a.istitle       a.lstrip        a.rindex        a.split         a.title
    a.casefold      a.expandtabs    a.isalnum       a.islower       a.isupper       a.maketrans     a.rjust         a.splitlines    a.translate
    a.center        a.find          a.isalpha       a.isnumeric     a.join          a.partition     a.rpartition    a.startswith    a.upper
    a.count         a.format        a.isdecimal     a.isprintable   a.ljust         a.replace       a.rsplit        a.strip         a.zfill
    a.encode        a.format_map    a.isdigit       a.isspace       a.lower         a.rfind         a.rstrip        a.swapcase 
    

    二、常用的字符串内建函数

    1、capitalize,字符串的第一个字符大写

    >>> a = 'today is a good day.'
    >>> a.capitalize()
    'Today is a good day.'
    

    2、 casefold,将所有字符小写,Unicode所有字符均适用

    >>> b
    'TODAY IS A GOOD DAY.'
    >>> b.casefold()
    'today is a good day.'
    

    3、lower,将所有字符小写,只适用ASCii

    >>> b
    'TODAY IS A GOOD DAY.'
    >>> b.lower()
    'today is a good day.'
    

    4、upper,将所有字符大写

    >>> a
    'today is a good day.'
    >>> a.upper()
    'TODAY IS A GOOD DAY.'
    

    5、center,返回一个原字符串居中,并使用空格填充至长度 width 的新字符串,语法:str.center(width[, fillchar])

    >>> a
    'today is a good day.'
    >>> a.center(40)
    '          today is a good day.          '
    

    6、count,用于统计字符串里某个字符出现的次数。可选参数为在字符串搜索的开始与结束位置,语法:str.count(sub, start= 0,end=len(string))

    >>> a
    'today is a good day.'
    >>> a.count('a')
    3
    >>> a.count('a', 5, -2)
    2
    

    7、encode,以 encoding 指定的编码格式编码字符串。errors参数可以指定不同的错误处理方案,语法:str.encode(encoding='UTF-8',errors='strict')

    errors -- 设置不同错误的处理方案。默认为 'strict',意为编码错误引起一个UnicodeError。 其他可能得值有 'ignore', 'replace', 'xmlcharrefreplace', 'backslashreplace' 以及通过 codecs.register_error() 注册的任何值。

    >>> c = '你好'
    >>> c.encode(encoding='utf-8')
    b'xe4xbdxa0xe5xa5xbd'
    

    8、decode,以 encoding 指定的编码格式解码字符串。默认编码为字符串编码,语法:str.decode(encoding='UTF-8',errors='strict')

    >>> d
    b'xe4xbdxa0xe5xa5xbd'
    >>> d.decode(encoding='utf-8')
    '你好'
    

    9、startwith,检查字符串是否是以指定子字符串开头,如果是则返回 True,否则返回 False。如果参数 beg 和 end 指定值,则在指定范围内检查,语法:str.startswith(str, beg=0,end=len(string))

    >>> a
    'today is a good day.'
    >>> a.startswith('today')
    True
    >>> a.startswith('day')
    False
    >>> a.startswith('day', 5)
    False
    >>> a.startswith('today', 5)
    False
    

    10、endwith,判断字符串是否以指定后缀结尾,如果以指定后缀结尾返回True,否则返回False。可选参数"start"与"end"为检索字符串的开始与结束位置,语法:str.endswith(suffix[, start[, end]])

    >>> a
    'today is a good day.'
    >>> a.endswith('day.')
    True
    >>> a.endswith('today.')
    False
    >>> a.endswith('day.', 5)
    True
    

    11、expandtabs,把字符串中的 tab 符号(' ')转为空格,tab 符号(' ')默认的空格数是 8,语法:str.expandtabs(tabsize=8)

    >>> e = '	today is 	a good day.		'
    >>> e
    '	today is 	a good day.		'
    >>> e.expandtabs(4)
    '    today is    a good day.     '
    

    12、find,检测字符串中是否包含子字符串 str ,如果指定 beg(开始) 和 end(结束) 范围,则检查是否包含在指定范围内,如果包含子字符串返回开始的索引值,否则返回-1,语法:str.find(str, beg=0, end=len(string))

    >>> a
    'today is a good day.'
    >>> a.find('a')
    3
    >>> a.find('a', 10)
    17
    >>> a.find('abc')
    -1

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

    >>> a
    'today is a good day.'
    >>> a.index('a')
    3
    >>> a.index('a', 10)
    17
    >>> a.index('abc', 10)
    Traceback (most recent call last):
      File "<console>", line 1, in <module>
    ValueError: substring not found

    14、isalnum,检测字符串是否由字母和数字组成

    >>> a = 'wang512'
    >>> a.isalnum()
    True
    >>> a = 'wang'
    >>> a.isalnum()
    True
    >>> a = '512'
    >>> a.isalnum()
    True
    >>> a = 'wang 512'
    >>> a.isalnum()
    False
    

    15、isalnum,检测字符串是否只由字母组成

    >>> a = 'wang'
    >>> a.isalpha()
    True
    >>> a = '512'
    >>> a.isalpha()
    False
    

    16、isdecimal ,检查字符串是否只包含十进制字符。这种方法只存在于unicode对象

    >>> a = '12345'
    >>> a.isdecimal()
    True
    >>> a = 'wang'
    >>> a.isdecimal()
    False
    

    17、isdigit,检测字符串是否只由数字组成

    >>> a = '12345'
    >>> a.isdigit()
    True
    >>> a = 'wang'
    >>> a.isdigit()
    False
    

    18、isidentifier,检测字符串是否以字母开头

    >>> a.isidentifier()
    False
    >>> a = 'wang'
    >>> a.isidentifier()
    True
    

    19、islower,检测字符串是否由小写字母组成。

    >>> a = "wang"
    >>> a.islower()
    True
    >>> a = "Wang"
    >>> a.islower()
    False
    

    20、isupper,检测字符串中所有的字母是否都为大写。

    >>> a = "WANG"
    >>> a.isupper()
    True
    >>> a = "Wang"
    >>> a.isupper()
    False
    

    21、isnumeric,检测字符串是否只由数字组成。这种方法是只针对unicode对象。

    >>> a = '12345'
    >>> a.isnumeric()
    True
    >>> a = 'w123'
    >>> a.isnumeric()
    False
    

    22、isprintable,包含所有可打印字符的字符串。

    23、isspace,检测字符串是否只由空格组成。

    24、istitile,检测字符串中所有的单词拼写首字母是否为大写,且其他字母为小写。

    25、join,将序列中的元素以指定的字符连接生成一个新的字符串,语法:str.join(sequence)

    >>> a = ['a', 'b', 'c', 'd']
    >>> ','.join(a)
    'a,b,c,d'
    

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

    >>> a = 'wang'
    >>> a.ljust(10, '>')
    'wang>>>>>>'
    

    27、rjust,返回一个原字符串右对齐,并使用空格填充至长度 width 的新字符串。如果指定的长度小于字符串的长度则返回原字符串,语法:str.rjust(width[, fillchar])

    >>> a = 'wang'
    >>> a.rjust(10, '<')
    '<<<<<<wang'
    

    28、split,通过指定分隔符对字符串进行切片,如果参数num 有指定值,则仅分隔 num 个子字符串,语法:str.split(str="", num=string.count(str)).

    >>> a = 'wang wang wang wang'
    >>> a.split('a', 3)
    ['w', 'ng w', 'ng w', 'ng wang']
    

    29、rsplit

    >>> a
    'wang wang wang wang'
    >>> a.rsplit('a', 3)
    ['wang w', 'ng w', 'ng w', 'ng']
    

    30、splitlines,按照行(' ', ' ', ')分隔,返回一个包含各行作为元素的列表,如果参数 keepends 为 False,不包含换行符,如果为 True,则保留换行符,语法:str.splitlines([keepends])

    >>> a = 'ab c
    
    de fg
    kl
    '
    >>> a.splitlines()
    ['ab c', '', 'de fg', 'kl']
    >>> a.splitlines(False)
    ['ab c', '', 'de fg', 'kl']
    >>> a.splitlines(True)
    ['ab c
    ', '
    ', 'de fg
    ', 'kl
    ']
    

    31、strip,用于移除字符串头尾指定的字符(默认为空格),语法:str.strip([chars])

    32、rstrip,删除 string 字符串末尾的指定字符(默认为空格),语法:str.rstrip([chars])

    33、lstrip,用于截掉字符串左边的空格或指定字符,语法:str.lstrip([chars])

    34、maketrans,用于创建字符映射的转换表,对于接受两个参数的最简单的调用方式,第一个参数是字符串,表示需要转换的字符,第二个参数也是字符串表示转换的目标,语法:str.maketrans(intab, outtab)

    注:两个字符串的长度必须相同,为一一对应的关系。

    35、translate,根据参数table给出的表(包含 256 个字符)转换字符串的字符, 要过滤掉的字符放到 del 参数中,语法:str.translate(table[, deletechars]);

    >>> intab = "aeiou"
    >>> outtab = "12345"
    >>> trantab = str.maketrans(intab, outtab)
    >>> s = 'abcdef'
    >>> s.translate(trantab)
    '1bcd2f'
    >>> trantab
    {97: 49, 101: 50, 105: 51, 111: 52, 117: 53}
    

    36、partition,用来根据指定的分隔符将字符串进行分割。如果字符串包含指定的分隔符,则返回一个3元的元组,第一个为分隔符左边的子串,第二个为分隔符本身,第三个为分隔符右边的子串。语法:str.partition(str)

    37、rpartition

    >>> a = "http://www.baidu.com ://sina"
    >>> a.partition('://')
    ('http', '://', 'www.baidu.com ://sina')
    >>> a.rpartition('://')
    ('http://www.baidu.com ', '://', 'sina')
    

    38、replace,把字符串中的 old(旧字符串) 替换成 new(新字符串),如果指定第三个参数max,则替换不超过 max 次。语法:str.replace(old, new[, max])

    str = "this is string example....wow!!! this is really string"
    print(str.replace("is", "was"))
    print(str.replace("is", "was", 3))
    

    39、rfind,字符串最后一次出现的位置(从右向左查询),如果没有匹配项则返回-1。语法:str.rfind(str, beg=0 end=len(string))

    str = "this is really a string example....wow!!!"
    substr = "is"
    
    print(str.rfind(substr))
    print(str.rfind(substr, 0, 10))
    print(str.rfind(substr, 10, 0))
    
    print(str.find(substr))
    print(str.find(substr, 0, 10))
    print(str.find(substr, 10, 0))
    

    40、rindex,返回子字符串 str 在字符串中最后出现的位置,如果没有匹配的字符串会报异常,你可以指定可选参数[beg:end]设置查找的区间。语法:str.rindex(str, beg=0 end=len(string))

    str1 = "this is string example....wow!!!"
    str2 = "is"
    
    print(str1.rindex(str2))
    print(str1.index(str2))
    

    41、swapcase,用于对字符串的大小写字母进行转换。

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

    str = "this is string example....wow!!!"
    print(str.title())
    

    43、zfill,指定长度的字符串,原字符串右对齐,前面填充0。语法:str.zfill(width)

    str = "this is string example....wow!!!"
    print(str.zfill(40))
    
  • 相关阅读:
    一阶段11.16
    视频(一阶段)
    一阶段需求分析
    sprint计划会议内容
    金管家NABCD分析
    四则运算
    返回一个整数数组中最大子数组的和(首尾相连)
    四则运算
    返回一个二维数组最大子数组的和
    返回一个数组 最大子数组的和
  • 原文地址:https://www.cnblogs.com/gundan/p/8079804.html
Copyright © 2011-2022 走看看