字串格式化:
| 代碼如下 |
複製代碼 |
format = “hello %s, %s enough for ya?” values = (‘world’,'hot’) print format % values |
結果:hello world, hot enough for ya?
註:如果不是在命令列執行,把print後面的用括弧括起來
與php類似但函數或方法名不一樣的地方:
explode/" target="_blank">php explode=> python split
php trim => python strip
php implode => python join
字串的切片是指截取字串的子串。Python 裡截取字串的子串相當方便。首先,先給一個變數賦值:
>>> word="Hello"
第一種切片操作是獲得字串的第 n 個字元所組成的字串:
Python 的“下標”也是從 0 開始的。Python 裡似乎沒有字元這種概念,只有“只有一個字元的字串”的概念。所以,我們不能像 C 一樣地通過指定“數組”下標來改變字串,比如以下代碼是錯誤的:
| 代碼如下 |
複製代碼 |
| >>> word[1]='o' |
出現提示:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'str' object does not support item assignment
Python 字串中的下標也可以是負數,表示從右向左的順序。但是請注意,自然語言中的字串“最後”一個字元,在 Python 裡是第 -1 個字元。並且 Python 認為 -0 = 0, 所以有以下結果:
| 代碼如下 |
複製代碼 |
>>> word[-0] 'H' >>> word[-1] 'o' |
Python 也可以切出含有多於一個字元的子串,下標間用冒號隔開:
| 代碼如下 |
複製代碼 |
>>> word[1:3] 'el' |
其實我們可以把 Python 字串的下標看成“字元間的空隙”,下圖能夠更好地展示 Python 下標的本質:
| 代碼如下 |
複製代碼 |
+---+---+---+---+---+ | H | e | l | l | o | +---+---+---+---+---+ 0 1 2 3 4 5 -5 -4 -3 -2 -1 -0
|
這樣你就不難理解下面語句的輸出了:
| 代碼如下 |
複製代碼 |
>>> word[3:1] '' >>> word[1:-1] 'ell' >>> word[-1:-3] '' |
也就是說,如果對於 Python 的下標,如果左邊數值標在左邊的空隙,右邊數值標在右邊的空隙,那麼這兩個空隙之間的內容將是這個運算式的值。反之,將會是Null 字元串。
若是在字串下標處寫了冒號,而冒號的某一邊,甚至兩邊的數值都是空的話,就表示取“最極端的值”,也就是儘可能地讓子串長:
| 代碼如下 |
複製代碼 |
>>> word[:] 'Hello' >>> word[1:] 'ello' >>> word[:-2] 'Hel' |
Python 中,用下標表示的字串子串,是唯讀。並且在記憶體中,應該是一個副本
python 字串的分割和組合
| 代碼如下 |
複製代碼 |
>>> s 'hello World! Everyone! This Is My First String!' >>> s.split() ['hello', 'World!', 'Everyone!', 'This', 'Is', 'My', 'First', 'String!'] >>> s.split(' ',4) ['hello', 'World!', 'Everyone!', 'This', 'Is My First String!'] >>> s.split('e') ['h', 'llo World! Ev', 'ryon', '! This Is My First String!'] >>> s.rsplit() ['hello', 'World!', 'Everyone!', 'This', 'Is', 'My', 'First', 'String!'] >>> s.rsplit(' ',4) ['hello World! Everyone! This', 'Is', 'My', 'First', 'String!'] >>> s.rsplit('e') ['h', 'llo World! Ev', 'ryon', '! This Is My First String!']
|
#s.split([sep, [maxsplit]]) 以sep是分隔字元,把s分割成一個list。sep預設為空白格。maxsplit是分割的次數,預設是對整個s進行分割
#s.rsplit([sep, [maxsplit]]) 和split()的區別是它是從s的串尾往前進行分割
| 代碼如下 |
複製代碼 |
>>> s=s.replace(' ','/n') >>> s 'hello/nWorld!/nEveryone!/nThis/nIs/nMy/nFirst/nString!' >>> s.splitlines() ['hello', 'World!', 'Everyone!', 'This', 'Is', 'My', 'First', 'String!'] >>> s.splitlines(True) ['hello/n', 'World!/n', 'Everyone!/n', 'This/n', 'Is/n', 'My/n', 'First/n', 'String!'] >>> s.splitlines(False) ['hello', 'World!', 'Everyone!', 'This', 'Is', 'My', 'First', 'String!'] >>> '/t'.join(s.splitlines()) 'hello/tWorld!/tEveryone!/tThis/tIs/tMy/tFirst/tString!' #s.splitlines([keepends]) 把s按照行分隔字元分成一個list。如果keepends為True則list的每個元素保留行分割符,如果為False則不保留分隔字元 #s.join(seq) 用s把seq序列串聯起來 |