%用法:
%s
%10s——右對齊,占位符10位
%-10s——左對齊,占位符10位
%.2s——截取2位字符串
%10.2s——10位占位符,截取兩位字符串
>>>string = 'hello world' >>>print('%s' % string) hello world >>>print('%20s' % string) hello world >>>print('%-20s' % string) hello world >>>print('%.2s' % string) he >>>print('%.10s' % string) hello worl >>>print('%10.4s' % string) hell >>>print('%-10.4s' % string) hell
format用法:
相對基本格式化輸出采用‘%’的方法,format()功能更強大,該函數把字符串當成一個模板,通過傳入的參數進行格式化,並且使用大括號‘{}’作為特殊字符代替‘%’
位置匹配
(1)不帶編號,即“{}”
(2)帶數字編號,可調換順序,即“{1}”、“{2}”
(3)帶關鍵字,即“{a}”、“{tom}”
>>>str1 = 'hello' >>>str2 = 'world' >>>print('{} {}'.format(str1, str2)) #不帶字段 hello world >>>print('{0} {1}'.format(str1, str2)) #帶數字編號 hello world >>>print('{1} {0} {1} {1}'.format(str1, str2)) # 無序 world hello world world >>>print('{a} {b}'.format(b = 'world', a = 'hello')) #代關鍵字 hello world >>>'{0}, {1}, {2}'.format('a', 'b', 'c') #通過位置匹配 'a, b, c' >>>'{}, {}, {}'.format('a', 'b', 'c') 'a, b, c' >>>'{2}, {1}, {0}'.format('a', 'b', 'c') 'c, b, a' >>>'{2}, {0}, {1}'.format(*'abc') 'c, a, b' >>>'{0}{0}{1}{0}{1}{1}'.format('abc', 'def') 'abcabcdefabcdefdef' >>>'info: {name}, {age}'.format(age = 20, name = 'dongdong') 'info: dongdong, 20' >>>height = {'tom': 175, 'lisi': 180} >>>"info:'lisi:'{lisi}, 'tom:'{tom}".format(**height) "info:'lisi:'180, 'tom:'175"