zoukankan      html  css  js  c++  java
  • 三、字符串操作

    引自:https://segmentfault.com/a/1190000004598007?_ea=663877#articleHeader7

    概览

    字符串大小写转换

    • str.capitalize() #将首字母转换成大写,需要注意的是如果首字没有大写形式,则返回原字符串。
    1 >>> 'root '.capitalize()
    2 'Root '
    3 >>> 'root ubuntu'.capitalize()
    4 'Root ubuntu'
    5 >>> '王root ubuntu'.capitalize()
    6 '王root ubuntu'
    首字母大写
    • str.lower()  # 将字符串转换成小写,其仅对 ASCII 编码的字母有效。
    1 # 'ß' 为德语小写字母,其有另一种小写 'ss', lower 方法无法转换
    ASCII转小写
    • str.casefold()
    1 >>> 'UBUNTU'.casefold()
    2 'ubuntu'
    3 >>> 'ß'.casefold()
    4 'ss'
    5 >>> ''.casefold()
    6 ''
    Unicode 编码转小写
    • str.swapcase()
    1 >>> '徐Dobi a123 ß'.swapcase()
    2 '徐dOBI A123 SS'
    对字符串字母的大小写进行反转。
    • str.title()
    1 >>> 'Hello world'.title()
    2 'Hello World'
    3 >>> '中文abc def 12gh'.title()
    4 '中文Abc Def 12Gh'
    5 >>> # 但这个方法并不完美:
    6 ... "they're bill's friends from the UK".title()
    7 "They'Re Bill'S Friends From The Uk"
    将字符串中每个“单词”首字母大写。其判断“单词”的依据则是基于空格和标点,所以应对英文撇好所有格或一些英文大写的简写时,会出错。
    • str.upper()
    1 >>> '中文abc def 12gh'.upper()
    2 '中文ABC DEF 12GH'
    将字符串所有字母变为大写,会自动忽略不可转成大写的字符

    字符串格式输出

    • str.center(width[, fillchar])
    1 >>> '12345'.center(10, '*')
    2 '**12345***'
    3 >>> '12345'.center(10)
    4 '  12345   '
    将字符串按照给定的宽度居中显示,可以给定特定的字符填充多余的长度,如果指定的长度小于字符串长度,则返回原字符串。
    • str.ljust(width[, fillchar]); str.rjust(width[, fillchar])
    1 >>> 'dobi'.ljust(10)
    2 'dobi      '
    3 >>> 'dobi'.ljust(10, '~')
    4 'dobi~~~~~~'
    5 >>> 'dobi'.ljust(3, '~')
    6 'dobi'
    7 >>> 'dobi'.ljust(3)
    8 'dobi'
    返回指定长度的字符串,字符串内容居左(右)如果长度小于字符串长度,则返回原始字符串,默认填充为 ASCII 空格,可指定填充的字符串
    • str.zfill(width)
     1 >>> "42".zfill(5)
     2 '00042'
     3 >>> "-42".zfill(5)
     4 '-0042'
     5 >>> 'dd'.zfill(5)
     6 '000dd'
     7 >>> '--'.zfill(5)
     8 '-000-'
     9 >>> ' '.zfill(5)
    10 '0000 '
    11 >>> ''.zfill(5)
    12 '00000'
    13 >>> 'dddddddd'.zfill(5)
    14 'dddddddd'
    用 '0' 填充字符串,并返回指定宽度的字符串。
    • str.expandtabs(tabsize=8)
    1 >>> tab = '1\t23\t456\t7890\t1112131415\t161718192021'
    2 >>> tab.expandtabs()
    3 '1       23      456     7890    1112131415      161718192021'
    4 >>> tab.expandtabs(4)
    5 '1   23  456 7890    1112131415  161718192021'
    6 >>> print(tab)
    7 1    23    456    7890    1112131415    161718192021
    用指定的空格替代横向制表符,使得相邻字符串之间的间距保持在指定的空格数以内。
    • str.format(^args, ^^kwargs)
    • str.format_map(mapping)
    1 >>> People = {'name':'john', 'age':56}
    2 >>> 'My name is {name},i am {age} old'.format_map(People)
    3 'My name is john,i am 56 old'
    类似 str.format(*args, **kwargs) ,不同的是 mapping 是一个字典对象。

    字符串搜索定位与替换

    • str.count(sub[, start[, end]])
    1 >>> text = 'outer protective covering'
    2 >>> text.count('e')
    3 4
    4 >>> text.count('e', 5, 11)
    5 1
    6 >>> text.count('e', 5, 10)
    7 0
    计数元素
    • str.find(sub[, start[, end]]); str.rfind(sub[, start[, end]])

     1 >>> text = 'outer protective covering'
     2 >>> text.find('er')
     3 3
     4 >>> text.find('to')
     5 -1
     6 >>> text.find('er', 3)
     7 3
     8 >>> text.find('er', 4)
     9 20
    10 >>> text.find('er', 4, 21)
    11 -1
    12 >>> text.rfind('er')
    13 20
    寻找元素,找不到返回-1
    • str.index(sub[, start[, end]]); str.rindex(sub[, start[, end]])

    1 >>> text = 'outer protective covering'
    2 >>> text.index('er')
    3 3
    4 >>> text.index('eraa')
    5 Traceback (most recent call last):
    6   File "<stdin>", line 1, in <module>
    7 ValueError: substring not found
    与 find() rfind() 类似,不同的是如果找不到,就会引发 ValueError。
    • str.replace(old, new[, count])

    1 >>> 'dog wow wow jiao'.replace('wow', 'wang', 1)
    2 'dog wang wow jiao'
    替换
    • str.lstrip([chars]); str.rstrip([chars]); str.strip([chars])

    1 >>> s = "  For you, a thousand times over. "
    2 >>> s.strip()  # 移除俩端空白
    3 'For you, a thousand times over.'
    4 >>> s.lstrip() #移除左边空白
    5 'For you, a thousand times over. '
    6 >>> s.rstrip() #移除右边空白
    7 '  For you, a thousand times over.'
    去除空白

    # 先注掉 static str.maketrans(x[, y[, z]]); str.translate(table)

    字符串的联合与分割

    • str.join(iterable)

     1 >>> '-'.join(['2012', '3', '12'])
     2 '2012-3-12'
     3 >>> '-'.join([2012, 3, 12])
     4 Traceback (most recent call last):
     5   File "<stdin>", line 1, in <module>
     6 TypeError: sequence item 0: expected str instance, int found
     7 >>> ','.join({'dobi':'dog', 'polly':'bird'})
     8 'dobi,polly'
     9 >>> ','.join({'dobi':'dog', 'polly':'bird'}.values())
    10 'dog,bird'
    用指定的字符串,连接元素为字符串的可迭代对象。
    • str.partition(sep); str.rpartition(sep)

    1 >>> 'dog wow wow jiao'.partition('wow')
    2 ('dog ', 'wow', ' wow jiao')
    3 >>> 'dog wow wow jiao'.partition('dog')
    4 ('', 'dog', ' wow wow jiao')
    5 >>> 'dog wow wow jiao'.rpartition('wow')
    6 ('dog wow ', 'wow', ' jiao')
    如果字符串包含指定的分隔符,则返回一个3元的元组,第一个为分隔符左边的子串,第二个为分隔符本身,第三个为分隔符右边的子串。
    • str.split(sep=None, maxsplit=-1); str.rsplit(sep=None, maxsplit=-1)

    1 >>> '1,2,3'.split(','), '1, 2, 3'.rsplit()
    2 (['1', '2', '3'], ['1,', '2,', '3'])
    3 >>> '1,2,3'.split(',', maxsplit=1),  '1,2,3'.rsplit(',', maxsplit=1)
    4 (['1', '2,3'], ['1,2', '3'])
    5 >>> ''.split()
    6 []
    7 >>> ''.split('a')
    8 ['']
    通过指定分隔符对字符串进行切片,如果参数 num 有指定值,则仅分隔 num 个子字符串

    # str.splitlines([keepends])

    字符串条件判断

    • str.endswith(suffix[, start[, end]]); str.startswith(prefix[, start[, end]])

    以什么开始、什么结束
    • str.isalnum()
    字符串和数字的任意组合,即为真。

    >>> 'hello assss22'.isalnum()
    False
    >>> 'helloassss22'.isalnum()
    True

    #str.isalpha()

    • str.isdecimal(); str.isdigit(); str.isnumeric()

    isdecimal() 方法检查字符串是否只包含十进制字符。这种方法只存在于unicode对象。
    isdigit() 方法用于判断指定字符是否为数字。
    isnumeric() 方法检测字符串是否只由数字组成。这种方法是只针对unicode对象。
    • str.isidentifier()
     1 >>> 'def'.isidentifier()
     2 True
     3 >>> 'with'.isidentifier()
     4 True
     5 >>> 'with.'.isidentifier()
     6 False
     7 >>> 'dobi_123'.isidentifier()
     8 True
     9 >>> '2dobi_123'.isidentifier()
    10 False
    11 >>> '_2dobi_123'.isidentifier()
    12 True
    判断字符串是否可为合法的标识符。
    • str.islower()
     1 >>> ''.islower()
     2 False
     3 >>> ''.islower()
     4 False
     5 >>> 'ss'.islower()
     6 True
     7 >>> 'Ab'.islower()
     8 False
     9 >>> '23'.islower()
    10 False
    11 >>> 'a王'.islower()
    12 True
    判断小写
    • str.isprintable()
    1 >>> 'dobi123'.isprintable()
    2 True
    3 >>> 'dobi123\n'.isprintable()
    4 False
    5 >>> 'dobi 123'.isprintable()
    6 True
    7 >>> ''.isprintable()
    8 True
    判断字符串的所有字符都是可打印字符或字符串为空。
    • str.isspace()
     1 >>> '\r\n\t'.isspace()
     2 True
     3 >>>  ''.isspace()
     4   File "<stdin>", line 1
     5     ''.isspace()
     6     ^
     7 IndentationError: unexpected indent
     8 >>>  ' '.isspace()
     9   File "<stdin>", line 1
    10     ' '.isspace()
    11     ^
    12 IndentationError: unexpected indent
    判断字符串中是否至少有一个字符,并且所有字符都是空白字符。
    • str.istitle()
    1 >>> 'How Python Works'.istitle()
    2 True
    3 >>> 'How Python WORKS'.istitle()
    4 False
    5 >>> ' '.istitle()
    6 False
    判断字符串中的字符是否是首字母大写,其会忽视非字母字符。
    • str.isupper()
    1 >>> ''.isupper()
    2 False
    3 >>> 'A徐'.isupper()
    4 True
    5 >>> 'Dobi'.isupper()
    6 False
    7 >>> 'DOBI\t 123'.isupper()
    8 True
    判断是否都大写,且最少有一个大写的。

    字符串编码

    • str.encode(encoding="utf-8", errors="strict")

    Python encode() 方法以 encoding 指定的编码格式编码字符串。errors参数可以指定不同的错误处理方案。

     

     

  • 相关阅读:
    selective search生成.mat文件
    2014 百度之星 1003 题解 Xor Sum
    hdu 2544 最短路
    表解锁
    第 10 章 数据结构
    MySQL Study之--Percona Server版本号
    const 不再迷茫
    opecv2 MeanShift 使用均值漂移算法查找物体
    server用JDBC对mysql数据库进行操作
    Django Admin site 显示问题
  • 原文地址:https://www.cnblogs.com/kongzhou/p/9007934.html
Copyright © 2011-2022 走看看