【Rollo的Python之路】Python:格式化输出:%与format

%用法:

1.0 整数的输出

%o —— oct 八进制
%d —— dec 十进制
%x —— hex 十六进制

>>> print('%o' % 20)
24
>>> print('%d' % 20)
20
>>> print('%x' % 20)
14

2.0 浮点数输出 %f

3.0 字符串输出 %d

>>> print('%s' % 'hello world')  # 字符串输出
hello world
print("%(u)s" % {'u':"sdads"}) #可以用字典与表达

format用法:

(1)不带编号,即“{}”

(2)带数字编号,可调换顺序,即“{1}”、“{2}”

(3)带关键字,即“{a}”、“{tom}”

>>> print('{} {}'.format('hello','world'))  # 不带字段
hello world
>>> print('{0} {1}'.format('hello','world'))  # 带数字编号
hello world
>>> print('{0} {1} {0}'.format('hello','world'))  # 打乱顺序
hello world hello
>>> print('{1} {1} {0}'.format('hello','world'))
world world hello
>>> print('{a} {tom} {a}'.format(tom='hello',a='world'))  # 带关键字
world hello world

猜你喜欢

转载自www.cnblogs.com/rollost/p/10776848.html