python内置数据结构之str

字符串

一个个字符串组成的有序的序列,是字符串的集合.
使用单引号、双引号、三引号引住的字符串序列.
字符串是不可变对象.
Python3起,字符串默认是Unicode类型

字符串join连接*

"String".join(iterable) -> str
    将可迭代对象连接起来,使用String作为分隔符
    可迭代对象本身元素都是字符串
    返回一个新字符串
    有引用对象时,无法使用


>>> l1
['1', '2', '3']
>>> '$'.join(l1)
'1$2$3'            # 新字符串
>>> ' '.join(l1)
'1 2 3'


>>> l2
[1, 2, 3]          # 可迭代对象为int类型
>>> ' '.join(l2)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: sequence item 0: expected str instance, int found


>>> l3
['1', ['a', 'b'], '2']       # 可迭代对象中有引用对象
>>> '\n'.join(l3)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: sequence item 1: expected str instance, list found


字符串分割*

分割字符串的方法分为两类
    split系
        将字符串安装分隔符分割成若干字符串,并返回列表
    partition系
        将字符串按照分隔符分割成两段,返回这2段和分隔符本身的元组
  • split
    Str.split(sep=None, maxsplit=-1) -> list of strings
    从左至右,返回字符串列表
    sep 指定分割符,缺省的情况下空白字符串作为分隔符,分隔符用引号引起
    maxsplit 指定分割的次数,-1 表示遍历整个字符串,范围超出时效果同-1

>>> s1
"i'm \t a spuer student."
>>> s1.split()       # 默认为空白字符(包括\t)
["i'm", 'a', 'spuer', 'student.']

>>> s1.split(sep='\t')
["i'm ", ' a spuer student.']
>>> s1.split(sep='s')
["i'm \t a ", 'puer ', 'tudent.']

>>> s1.split(sep='s',maxsplit=1)
["i'm \t a ", 'puer student.']
>>> s1.split(sep='s',maxsplit=2)
["i'm \t a ", 'puer ', 'tudent.']
>>> s1.split(sep='s',maxsplit=3)
["i'm \t a ", 'puer ', 'tudent.']
>>> s1.split(sep='s',maxsplit=-2)       # 次数范围不合法,默认同-1
["i'm \t a ", 'puer ', 'tudent.']
  • rsplit
    Str.rsplit(sep=None, maxsplit=-1) -> list of strings
    从右至左,返回字符串列表,其它同split

>>> s1
"i'm \t a spuer student."
>>> s1.rsplit(sep='t')
["i'm \t a spuer s", 'uden', '.']
>>> s1.rsplit(sep='t',maxsplit=1)    # 从右至左,以't'为分隔符
["i'm \t a spuer studen", '.']
>>> s1.rsplit(sep='t',maxsplit=2)
["i'm \t a spuer s", 'uden', '.']
  • splitlines
    Str.splitlines([keepends]) -> list of strings
    按照换行符来切分字符串
    keepends 指的是是否保留行分隔符
    行分隔符包括\n、\r\n、\r等

>>> print('ab c\n\nde fg\rkl\r\n')
ab c

kl fg

>>> 'ab c\n\nde fg\rkl\r\n'.splitlines()
['ab c', '', 'de fg', 'kl']
>>> 'ab c\n\nde fg\rkl\r\n'.splitlines(True)
['ab c\n', '\n', 'de fg\r', 'kl\r\n']
  • partition
    Str.partition(sep) -> (head, sep, tail)
    从左至右,遇到分隔符就把字符串分割成两部分,返回头、分隔符、尾三部分的三元组;如果没有找到分隔符,就返回头、2个空元素的元组
    sep 分割字符串,必须指定

>>> s2
'/a/b/c'
>>> s2.partition('b')     # 以'b'为分隔符,切成两部分
('/a/', 'b', '/c')
  • rpartition
    Str.rpartition(sep) -> (head, sep, tail)
    从右至左,其它同partition

>>> s2
'/a/b/c'
>>> s2.rpartition('/')
('/a/b', '/', 'c')
  • 字符串大小写(做判断时使用)

        upper()、lower()、swapcase()
        全大写、全小写、大小写交换
  • 字符串排版

    title() -> str
        每个单词首字符大写
    capitalize() -> str
        首个单词的首字符大写
    center(width[,fillchar]) -> str
        字符居中
        width 打印的总宽度
        fillchar 两侧填充的字符
    zfill(width) -> str
        width 打印的总宽度(包括原字符串),原字符串右对齐,左侧用0填充
    ljust(width[,fillchar]) -> str 左对齐
    rjust(width[,fillchar]) -> str 右对齐

字符串修改*

  • replace
    Str.replace(old, new[, count]) -> str
    字符串中找到匹配替换为新子串,返回新字符串
    count表示替换次数,不指定表示全部替换

>>> 'aaa'.replace('a','b')
'bbb'
>>> 'aaa'.replace('a','b',2)
'bba'
  • strip
    Str.strip([chars]) -> str
    从字符串两端去除指定的字符集chars中的所有字符
    如果chars没有指定,默认去除两端的空白字符

>>> s1
' abccba '
>>> s1.strip()      # 去除空白字符
'abccba'
>>> s1.strip('a')   # 从两端开始扫描,去除字符最前方的字符'a'
' abccba '
>>> s1.strip(' a')  # 去除空白字符和'a'
'bccb'
>>> s1.strip(' abc') # 去除字符集' abc'
''
  • lstrip
    Str.lstrip([chars]) -> str 
    从左开始去除

  • rstrip
    Str.rstrip([chars]) -> str
    从右开始去除

字符串查找*

  • find
    S.find(sub[, start[, end]]) -> int
    在指定区域[start,end) ,从左至右,查找子串sub.找到返回子串首字符索引,没找到返回-1

  • rfind
    S.rfind(sub[, start[, end]]) -> int
    在指定区域[start,end) ,从右至左,查找子串sub.找到返回子串首字符索引,没找到返回-1

>>> s1
' abccba '
>>> s1.find('a')  # 从左至右找
1
>>> s1.rfind('a')  # 从右至左找
6

>>> s1.find('a',1)  # 从索引为1的位置开始查找
1
>>> s1.find('a',2)  # 从索引为2的位置开始查找
6
>>> s1.find('a',-2) # 从索引为-2的位置开始查找
6
  • index
    S.index(sub[, start[, end]]) -> int
    同find,但没有找到时抛出异常

  • rindex
    S.index(sub[, start[, end]]) -> int
    同rfind,但没有找到时抛出异常

  • count
    S.count(sub[, start[, end]]) -> int
    在指定的区间[start,end),从左至右,统计子串sub出现的次数

>>> s1
' abccba '
>>> s1.count('a')
2
  • len(string)
    返回字符串的长度,即字符的个数

注意:

    index和count方法都是O(n)
    随着列表数据规模的增大,而效率下降


字符串判断*

  • startswith
    S.startswith(prefix[, start[, end]]) -> bool
    在指定区间[start,end),字符串是否是prefix开头

  • endswith
    S.endswith(suffix[, start[, end]]) -> bool
    在指定区间[start,end),字符串是否是suffix结尾

>>> s1
'my name is pythoner'
>>> s1.endswith('pythoner')
True
>>> s1.endswith('er')
True
>>> s1.startswith('my')
True
>>> s1.startswith('My')
False

字符串判断is系列
isdigit() 是否所有字符全部是数字0-9
S.isdigit() -> bool
isidentifier() -> bool
是不是字母和下划线开头,其它都是字母、数字、下划线

>>> s1
'my name is pythoner'
>>> s1.isidentifier()
False
>>> s2='_da1213'
>>> s2.isidentifier()
True


字符串格式化***


format函数格式字符串语法
    "{} {xxx}".format(*args,**kwargs) -> str
    args是位置参数,是一个元组
    kwargs是关键字参数,是一个字典
    花括号表示占位符
    {}表示按照顺序匹配位置参数,{n}表示取位置参数索引为n的值
    {xxx}表示在关键字参数中搜索名称一致的对象
    {{}} 表示打印花括号本身


- 位置参数

    >>> "{}:{}".format('0.0.0.0',80)
    '0.0.0.0:80'
    按照位置顺序用位置参数替换前面的格式字符串的占位符


- 关键字参数或命名参数

    >>> '{server} {1}:{0}'.format(80,'0.0.0.0',server='Web Server')
    'Web Server 0.0.0.0:80'
    位置参数按照序号匹配,关键字参数按照名称匹配


- 访问元素

    >>> '{0[0]}:{0[1]}:{0[2]}'.format([1,2,3])
    '1:2:3'
    访问列表对象的元素


- 对象属性访问

    >>> from collections import namedtuple
    >>> Point = namedtuple('Point','x,y')
    >>> ins = Point(1,2)
    >>> '{0.x}:{0.y}'.format(ins)        # ins类的属性
    '1:2'


- 对齐

左对齐 <
右对齐 >
宽度  
填充 

>>> '{0}*{1}={2:>3}'.format(2,3,2*3)
'2*3=  6'
>>> '{0}*{1}={2:>03}'.format(2,3,2*3)
'2*3=006'


- 进制

>>> "{0:x} {0:o} {0:b} {0:d}".format(10)
'a 12 1010 10'


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章