1. 程式人生 > >python-12 資料結構 字串

python-12 資料結構 字串

一般操作

>>> str1="hello"
>>> 2*str1
'hellohello'
>>> min(str1)
'e'

編碼和解碼

>>> str1 = "編碼和解碼"
>>> str1
'編碼和解碼'
>>> b1 = str1.encode(encoding="cp936")
>>> b1
b'\xb1\xe0\xc2\xeb\xba\xcd\xbd\xe2\xc2\xeb'
>>> b1.decode(encoding="cp936")
'編碼和解碼'

不指定預設是utf-8

格式化?

>>> "結果為%f"%88
'結果為88.000000'

>>> "%s  %d  %f"%("ddd",90,12.3)
'ddd  90  12.300000'

字典
>>> "%(lang)d"%{"lang":2323}
'2323'

字串格式化?
%a
%s
%r

format

>>> format(85,"0.5f")
'85.00000'

>>> format(0.5,"%")
'50.000000%'

>>> "{2},{1},{0}".format("a","b","c")
'c,b,a'

>>> str.format_map("{name:s},{age:d}",{"name":"tom","age":20})
'tom,20'