1. 程式人生 > >Python3常用資料結構及方法介紹(三)——字串

Python3常用資料結構及方法介紹(三)——字串

三.字串
特點:不可更改
1.基本操作(同其他序列)
①索引

>>> 'python'[2]
't'

②分片

>>> 'beauty'[0:2]
'be'
>>> 'beauty'[::2]
'bat'

③相加/相乘

>>> 'love'+'python'
'lovepython'
>>> 'loveyou'*2
'loveyouloveyou'

④成員資格

>>> if 'o' in 'python':print('OK')
... 
OK
>>> if not 'a' in 'bcd':print('right')
... 
right

⑤len/max/min

>>> len('what')
4
>>> max('fantastic')
't'
>>> min('aceg')
'a'

2.字串格式化操作

>>> '%s is %s' %('python','easy')
'python is easy'
>>> '%s + %s = %s' %(2,3,5)
'2 + 3 = 5'

3.字串方法
①find

>>> 'great'.find('e')
2

②join

>>> ''.join(['g','r','e','a','t'])
'great'

③lower

>>> 'GREAT WALL'.lower()
'great wall'

④upper

>>> 'great wall'.upper()
'GREAT WALL'

⑤replace

>>> '1234562345'.replace('2','0')
'1034560345'

⑥split

>>> '1+2+3+4+5'.split('+')
['1', '2', '3', '4', '5']
>>> '1 2 3 4 5 '.split()
['1', '2', '3', '4', '5']

⑦strip

>>> '  python  '.strip()
'python'

⑧translate(自python3起,用str.maketrans)

>>> 'python'.translate(str.maketrans('pt','ab'))
'aybhon'

4.字串逆序輸出

>>> print('python'[::-1])
nohtyp
>>> ''.join(reversed('python'))
'nohtyp'

一.列表 list

二.元組 tuple

四.字典 dict

未完待續……