%用法:
%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"