首页 > 编程语言 > 详细

Python—格式化输出

时间:2019-08-01 23:07:54      阅读:98      评论:0      收藏:0      [点我收藏+]

Python提供了很多种格式化方式(包括但不限于以下几种):

[,]分隔

name = 'jack'
age = -0.5

print(name, 'is', age, 'years old.')
jack is -0.5 years old.

[+]号

name = 'jack'
age = -0.5

print(name + ' is ' + str(age) + ' years old.')
jack is -0.5 years old.

[%]号

name = 'jack'
age = -0.5

print('%s is %.2f years old.'%(name, age))
jack is -0.50 years old.

f 字符串

name = 'jack'
age = -0.5

print(f'name is {name}')
print(f'{name}\'s age is {age}')
print(f'{name.upper()}')
print(f'{name[0]}')
name is jack
jack's age is -0.5
JACK
j

str.format方法

name = 'jack'
age = -0.5

print('name={}, age={}'.format(name, age))
print('name={1}, age={0}'.format(age, name))
print('name={a}, age={b}'.format(a=name, b=age))
name=jack, age=-0.5
name=jack, age=-0.5
name=jack, age=-0.5

format内置函数

name = 'jack'
age = -0.5

print(format(name))
print(format(age, '5f'))
jack
-0.500000

Formatter类

from string import Formatter

form = Formatter()
name = 'jack'
age = -0.5

print(form.format('name={}, age={}', name, age))
print(form.format('name={1}, age={0}', age, name))
print(form.format('name={a}, age={b}', b=age, a=name))
name=jack, age=-0.5
name=jack, age=-0.5
name=jack, age=-0.5

printf风格

name = 'jack'
age = -0.5

print('%(x)s'%{'x':name})
print('%(x).5f'%{'x':age})
jack
-0.50000

Template

from string import Template

name = 'jack'
age = -0.5

s = Template('$a is $b years old').substitute(a=name, b=age)
print(s)
jack is -0.5 years old

Python—格式化输出

原文:https://www.cnblogs.com/malinqing/p/11285603.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!