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'


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