[Learning Python] Chapter 7 String Fundamentals

1, 字符串的鏈接concatenate有兩種方式:
A:直接寫在一塊兒:express

>>> title = "Meaning " 'of' " Life" # Implicit concatenation
>>> title
'Meaning of Life'

B:使用+號ui

2,raw string: 在string前面加r,就會是string的再也不具備轉義功能。
應該注意的是,若是str的末尾是, Python仍然會將這個 和它後面的引號轉義輸出。這時候就不要用raw string了。this

3,Triple quotes code multiline block strings: 三個引號(單引號或者雙引號)能夠作創造多行的strings。此時不要在這裏面的右邊加入comment,不然會被當作string。spa

4,triple quotes還能夠用來暫時的是某段代碼disable。以下面:code

X = 1
"""
import os # Disable this code temporarily
print(os.getcwd())
"""
Y = 2

5,字符串能夠進行切片操做,以截取某段字符:orm

>>> S = 'spam'
>>> S[0], S[−2] # Indexing from front or end 進行index操做
('s', 'a')
>>> S[1:3], S[1:], S[:−1] # Slicing: extract a section
('pa', 'pam', 'spa') # slice操做

6,切片的時候,包括寫在左邊的值,不包括寫在右邊的值。ip

7,三個參數的切片,X[I:J:K], 其中K表示步進step,若是不寫K,則表示K位默認值+1.ci

8,步進能夠是複數,這樣的切片將獲得倒着的字符串:字符串

例子一:步進step = -1,得到倒序的字符串‘olleh’。get

>>> S = 'hello'
>>> S[::.1] # Reversing items
'olleh'

例子二:這裏仍然包括offset 5,不包括offset 1,該記住:切片包括寫在左邊的offset,不包括寫在右邊的offset。

>>> S = 'abcedfg'
>>> S[5:1:−1] # Bounds roles differ
'fdec'

9,切片有時候能夠用於截取文本中的某行字。一般來說,每一行的結尾都是n,使用[:-1]便可以把n這個byte給去掉。雖然,人們更經常使用的是line.rstrip方法,由於有可能某行的行末未必有n.

10,ord()能夠將某個字符轉換爲ASCII碼,而chr則能夠將ASCII碼還原爲所對應的字符。

11,int(‘1101’,2) 這個式子能夠將二進制數1101,轉換爲十進制的integer。須要注意的是,1101須要加上‘’,2表示base。

12,string有個replace的方法,能夠用來產生新的string。

>>> S = 'splot'
>>> S = S.replace('pl', 'pamal')
>>> S
'spamalot'

若是想要讓Python只替換i次,須要填寫它的第三個參數:

>>> S.replace('SPAM', 'EGGS', 1) # Replace one
'xxxxEGGSxxxxSPAMxxxx'

13,雖然string是immutable sequence, 須要作in-place change的話仍是能夠先將string轉換爲list,在用’’.join(some_list)的方法生成一個新的string。

14,string有一個split方法,能夠將string以某特定的分界符將string切細,並返回一個list。

例子一:split()裏面沒有參數,表明的是whitespce(空格, 製表位,換行等,數量不限)

>>> line = 'aaa bbb ccc'
>>> cols = line.split()
>>> cols
['aaa', 'bbb', 'ccc']

例子二:以逗號做爲分界符,將string切細並返回一個list。

>>> line = 'bob,hacker,40'
>>> line.split(',')
['bob', 'hacker', '40']

15,string的其餘有用的方法:rstrip、upper、isalpha、endswith、startswith

16,格式化string有兩種方法:
A: 相似於C語言的方法,String formatting expressions: '...%s...' % (values)
B: 從C#/.NET引進的方法:
String formatting method calls: '...{}...'.format(values)

17, 針對方法A,下面的表格是格式的說明:

18,在%左邊的格式是這樣的:
%(keyname)widthtypecode
Keyname表示若是是dictionary的引用,這裏寫dictionary的key;
Flags: -號表示向左靠齊,0表示補零
Width 表示總共的位數
.precision 表示小數點右邊要有多少位小數

19,下面的例子表示暫時不知道要有多少位小數,待傳入值得時候肯定:

>>> '%f, %.2f, %.*f' % (1/3.0, 1/3.0, 4, 1/3.0)
'0.333333, 0.33, 0.3333'  #這裏最後選擇了4位小數。

20,dictionary能夠做爲參數傳入到這樣的式子中:

>>> '%(qty)d more %(food)s' % {'qty': 1, 'food': 'spam'}
'1 more spam'

21,B方法:string format method 有以下4種基礎類型:
Pass

22,更加複雜的以下面這種:

>>> somelist = list('SPAM')
>>> somelist
['S', 'P', 'A', 'M']
>>> 'first={0[0]}, third={0[2]}'.format(somelist)
'first=S, third=A'

23, A 方法使用 % 例子大全:

23.1 若是有兩個參數,須要用括號將他們包圍起來,括號前加%

>>> 'That is %d %s bird!' % (1, 'dead') # Format expression
That is 1 dead bird!

23.2 賦給一個variable代替%後面的內容

>>> exclamation = 'Ni'
>>> 'The knights who say %s!' % exclamation # String substitution
'The knights who say Ni!'

23.3 全部類型均可以使用%s,由於全部的object均可以轉換爲string。

>>> '%s -- %s -- %s' % (42, 3.14159, [1, 2, 3]) # All types match a %s target
'42 -- 3.14159 -- [1, 2, 3]'

23.4 –號表示向左靠齊。0表示用0補夠數,6表示總共有6位

>>> x = 1234
>>> res = 'integers: ...%d...%−6d...%06d' % (x, x, x)
>>> res
'integers: ...1234...1234 ...001234'

23.5 小數點後面的數字表示小數位數

>>> '%−6.2f | %05.2f | %+06.1f' % (x, x, x)
'1.23 | 01.23 | +001.2'

23.6 %配合字典dictionary使用

>>> '%(qty)d more %(food)s' % {'qty': 1, 'food': 'spam'}
'1 more spam'

23.7 字典配合使用

>>> reply = """
Greetings...
Hello %(name)s!
Your age is %(age)s
"""
>>> values = {'name': 'Bob', 'age': 40} # Build up values to substitute
>>> print(reply % values) # Perform substitutions
Greetings...
Hello Bob!
Your age is 40

23.8字典配合使用

>>> template = '%(motto)s, %(pork)s and %(food)s'
>>> template % dict(motto='spam', pork='ham', food='eggs')
'spam, ham and eggs'

24 B方法例子

24.1經過絕對位置

>>> template = '{0}, {1} and {2}' # By position
>>> template.format('spam', 'ham', 'eggs')
'spam, ham and eggs'

24.2 經過key,能夠不用引號

>>> template = '{motto}, {pork} and {food}' # By keyword
>>> template.format(motto='spam', pork='ham', food='eggs')
'spam, ham and eggs'

24.3 混合

>>> template = '{motto}, {0} and {food}' # By both
>>> template.format('ham', motto='spam', food='eggs')
'spam, ham and eggs'

24.4 經過相對位置

>>> template = '{}, {} and {}' # By relative position
>>> template.format('spam', 'ham', 'eggs') # New in 3.1 and 2.7
'spam, ham and eggs'

24.5 字典,屬性一塊兒混合使用,下面的1表示format括號裏的第2個參數,0表示字典裏的第一個參數。

>>> import sys
>>> 'My {1[kind]} runs {0.platform}'.format(sys, {'kind': 'laptop'})
'My laptop runs win32' 
>>> 'My {map[kind]} runs {sys.platform}'.format(sys=sys, map={'kind': 'laptop'})
'My laptop runs win32'

24.6 下面,0表示format()括號內的第一個參數,1表示第二個參數。冒號後面是格式,>號表示向左靠齊,<表示向左靠齊,10表示的是總須要十位

>>> '{0:>10} = {1:<10}'.format('spam', 123.4567)
' spam = 123.4567 '

24.7 若是冒號前面不寫,則按照相對位置替換。

>>> '{:>10} = {:<10}'.format('spam', 123.4567)
' spam = 123.4567 '

24.8 在格式的位置用e f g來約束

>>> '{0:e}, {1:.3e}, {2:g}'.format(3.14159, 3.14159, 3.14159)
'3.141590e+00, 3.142e+00, 3.14159'
>>> '{0:f}, {1:.2f}, {2:06.2f}'.format(3.14159, 3.14159, 3.14159)
'3.141590, 3.14, 003.14'

24.9 在格式的位置用x,o,b來約束,進而顯示十六進制、八進制、二進制數

>>> '{0:X}, {1:o}, {2:b}'.format(255, 255, 255) # Hex, octal, binary
'FF, 377, 11111111'

24.10 這裏的1對應的是括號裏的4,表示的是小數位數

>>> '{0:.{1}f}'.format(1 / 3.0, 4) # Take value from arguments
'0.3333'

24.11 在d前面,或者e,f,g等前面加上逗號,能夠每三個數用逗號隔開

>>> '{0:,d}'.format(999999999999)
'999,999,999,999'

24.12 逗號要寫在小數點的前面,若是他們都須要用到的話

>>> '{:,.2f}'.format(296999.2567)
'296,999.26'

24.13 顯示tuple

>>> '{0}'.format((1.23,)) # Single value that is a tuple
'(1.23,)'

24.14 用關鍵字,對應於format裏面的關鍵字

>>> '{num:d} = {title:s}'.format(num=7, title='Strings')
'7 = Strings'
相關文章
相關標籤/搜索