【HC】Python format 格式化函数
http://cdn.u1.huluxia.com/g3/M02/57/E2/wKgBOV3apNOAK433AAFAIevZ-vc733.jpg
一种格式化字符串的函数 str.format(),它增强了字符串格式化的功能。http://cdn.u1.huluxia.com/g3/M02/57/E2/wKgBOV3apNKAHCfbAAALPFR943E118.jpg
基本语法是通过 {} 和 : 来代替以前的 % 。
format 函数可以接受不限个参数,位置可以不按顺序。
这么玩:
# 不设置指定位置,按默认顺序
expenses = (
['Rent', 1000],
['Gas', 100],
['Food',300],
['Gym', 50],
)
for x, i in expenses:
print('a:{} b:{}'.format(x, i))
结果:
a:Rent b:1000
a:Gas b:100
a:Food b:300
a:Gym b:50
# 设置指定位置
expenses = (
['Rent', 1000],
['Gas', 100],
['Food',300],
['Gym', 50],
)
for x, i in expenses:
print('a:{0} b:{1}'.format(x, i))
结果:a:Rent b:1000
a:Gas b:100
a:Food b:300
a:Gym b:50
print('a:{0} b:{1}'.format(x, i))
结果:a:1000 b:Rent
a:100 b:Gas
a:300 b:Food
a:50 b:Gym
#也可以设置参数:
print("网站名:{name}, 地址 {url}".format(name="xxx", url="www.xxx.com"))
网站名:xxx, 地址 www.xxx.com
# 通过字典设置参数
data = {'name':'xxx', 'url':'www.xxx.com'}
print("网站名:{name}, 地址 {url}".format(**data))
# 通过列表索引设置参数
my_list = ['xxx', 'www.xxx.com']
print("网站名:{0}, 地址 {0}".format(my_list))# "0" 是必须的
#也可以向 str.format() 传入对象
class AssignValue(object):
def __init__(self, num):
self.num = num
my_num = AssignValue(6)
print('num 为: {0.num}'.format(my_num))# "0" 是可选的
print('num 为: {my_num.num}'.format(my_num=my_num))
# value 为: 6
# value 为: 6
粘过来的:http://cdn.u1.huluxia.com/g3/M02/57/E2/wKgBOV3apNGAYZ3SAAD0AItkApw241.jpg
expenses = (
['Rent', 1000],
['Gas', 100],
['Food',300],
['Gym', 50],
)
for x, i in expenses:
print('a:{} b:{}'.format(x, i))
结果:http://cdn.u1.huluxia.com/g3/M02/57/E2/wKgBOV3apNKAJeDyAAC0AHmejb0861.jpg
a:Rent b:1000
a:Gas b:100
a:Food b:300
a:Gym b:50
页:
[1]