在线观看不卡亚洲电影_亚洲妓女99综合网_91青青青亚洲娱乐在线观看_日韩无码高清综合久久

鍍金池/ 教程/ Python/ 字符串
基礎(chǔ)
itertools
HTTP 服務(wù)
hashlib
閉包
文件和目錄
單元測試
使用 @property
標(biāo)準(zhǔn)模塊
陌生的 metaclass
Base64
進(jìn)程、線程和協(xié)程
讀寫二進(jìn)制文件
匿名函數(shù)
輸入和輸出
Click
元組
字符編碼
partial 函數(shù)
參考資料
collections
協(xié)程
類和實(shí)例
Python 之旅
定制類和魔法方法
常用數(shù)據(jù)類型
繼承和多態(tài)
ThreadLocal
HTTP 協(xié)議簡介
Requests 庫的使用
讀寫文本文件
列表
os 模塊
迭代器 (Iterator)
正則表達(dá)式
集合
上下文管理器
異常處理
你不知道的 super
定義函數(shù)
datetime
資源推薦
字典
slots 魔法
hmac
第三方模塊
進(jìn)程
類方法和靜態(tài)方法
函數(shù)參數(shù)
高階函數(shù)
函數(shù)
re 模塊
高級特性
線程
argparse
生成器
結(jié)束語
字符串
map/reduce/filter
函數(shù)式編程
Celery
裝飾器

字符串

字符串也是一種序列,因此,通用的序列操作,比如索引,分片,加法,乘法等對它同樣適用。比如:

>>> s = 'hello, '
>>> s[0]            # 索引
'h'
>>> s[1:3]          # 分片
'el'
>>> s + 'world'     # 加法
'hello, world'
>>> s * 2           # 乘法
'hello, hello, '

但需要注意的是,字符串和元組一樣,也是不可變的,所以你不能對它進(jìn)行賦值等操作:

>>> s = 'hello'
>>> s[1] = 'ab'    # 不能對它進(jìn)行賦值
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'str' object does not support item assignment

除了通用的序列操作,字符串還有自己的方法,比如 join, lower, upper 等。字符串的方法特別多,這里只介紹一些常用的方法,如下:

  • find
  • split
  • join
  • strip
  • replace
  • translate
  • lower/upper

find

find 方法用于在一個(gè)字符串中查找子串,它返回子串所在位置的最左端索引,如果沒有找到,則返回 -1。

看看例子:

>>> motto = "to be or not to be, that is a question"
>>> motto.find('be')            # 返回 'b' 所在的位置,即 3
3
>>> motto.find('be', 4)         # 指定從起始位置開始找,找到的是第 2 個(gè) 'be'
16
>>> motto.find('be', 4, 7)      # 指定起始位置和終點(diǎn)位置,沒有找到,返回 -1
-1

split

split 方法用于將字符串分割成序列。

看看例子:

>>> '/user/bin/ssh'.split('/')         # 使用 '/' 作為分隔符
['', 'user', 'bin', 'ssh']
>>> '1+2+3+4+5'.split('+')             # 使用 '+' 作為分隔符
['1', '2', '3', '4', '5']
>>> 'that    is a   question'.split()  # 沒有提供分割符,默認(rèn)使用所有空格作為分隔符
['that', 'is', 'a', 'question']

需要注意的是,如果不提供分隔符,則默認(rèn)會使用所有空格作為分隔符(空格、制表符、換行等)。

join

join 方法可以說是 split 的逆方法,它用于將序列中的元素連接起來。

看看例子:

>>> '/'.join(['', 'user', 'bin', 'ssh'])
'/user/bin/ssh'
>>>
>>> '+'.join(['1', '2', '3', '4', '5'])
'1+2+3+4+5'
>>> ' '.join(['that', 'is', 'a', 'question'])
'that is a question'
>>> ''.join(['h', 'e', 'll', 'o'])
'hello'
>>> '+'.join([1, 2, 3, 4, 5])          # 不能是數(shù)字
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: sequence item 0: expected string, int found

strip

strip 方法用于移除字符串左右兩側(cè)的空格,但不包括內(nèi)部,當(dāng)然也可以指定需要移除的字符串。

看看例子:

>>> '  hello world!   '.strip()                # 移除左右兩側(cè)空格
'hello world!'
>>> '%%%   hello world!!!  ####'.strip('%#')   # 移除左右兩側(cè)的 '%' 或 '#'
'   hello world!!!  '
>>> '%%%   hello world!!!  ####'.strip('%# ')  # 移除左右兩側(cè)的 '%' 或 '#' 或空格
'hello world!!!'

replace

replace 方法用于替換字符串中的所有匹配項(xiàng)。

看看例子:

>>> motto = 'To be or not To be, that is a question'
>>> motto.replace('To', 'to')        # 用 'to' 替換所有的 'To',返回了一個(gè)新的字符串
'to be or not to be, that is a question'
>>> motto                            # 原字符串保持不變
'To be or not To be, that is a question'

translate

translate 方法和 replace 方法類似,也可以用于替換字符串中的某些部分,但 translate 方法只處理單個(gè)字符

translate 方法的使用形式如下:

str.translate(table[, deletechars]);

其中,table 是一個(gè)包含 256 個(gè)字符的轉(zhuǎn)換表,可通過 maketrans 方法轉(zhuǎn)換而來,deletechars 是字符串中要過濾的字符集。

看看例子:

>>> from string import maketrans
>>> table = maketrans('aeiou', '12345')
>>> motto = 'to be or not to be, that is a question'
>>> motto.translate(table)
't4 b2 4r n4t t4 b2, th1t 3s 1 q52st34n'
>>> motto
'to be or not to be, that is a question'
>>> motto.translate(table, 'rqu')        # 移除所有的 'r', 'q', 'u'
't4 b2 4 n4t t4 b2, th1t 3s 1 2st34n'

可以看到,maketrans 接收兩個(gè)參數(shù):兩個(gè)等長的字符串,表示第一個(gè)字符串的每個(gè)字符用第二個(gè)字符串對應(yīng)位置的字符替代,在上面的例子中,就是 'a' 用 '1' 替代,'e' 用 '2' 替代,等等,注意,是單個(gè)字符的代替,而不是整個(gè)字符串的替代。因此,motto 中的 o 都被替換為 4,e 都被替換為 2,等等。

lower/upper

lower/upper 用于返回字符串的大寫或小寫形式。

看看例子:

>>> x = 'PYTHON'
>>> x.lower()
'python'
>>> x
'PYTHON'
>>>
>>> y = 'python'
>>> y.upper()
'PYTHON'
>>> y
'python'

小結(jié)

  • 字符串是不可變對象,調(diào)用對象自身的任意方法,也不會改變該對象自身的內(nèi)容。相反,這些方法會創(chuàng)建新的對象并返回。
  • translate 針對單個(gè)字符進(jìn)行替換。

參考資料

  • 《python 基礎(chǔ)教程》
上一篇:單元測試下一篇:資源推薦