python的format怎么用?
python的format函数用法
它增强了字符串格式化的功能。基本语法是通过 {} 和 : 来代替以前的 % 。format 函数可以接受不限个参数,位置可以不按顺序。
**例一:**format 函数可以接受不限个参数,位置可以不按顺序。
"{} {}".format("hello", "world") # 不设置指定位置,按默认顺序
运行结果:'hello world'
"{0} {1}".format("hello", "world") # 设置指定位置
运行结果:'hello world'
"{1} {0} {1}".format("hello", "world") # 设置指定位置
运行结果:'world hello world' 例二:也可以设置参数。
print("网站名:{name}, 地址 {url}".format(name="Python教程", url="HdhCmsTestpy.cn"))
# 通过字典设置参数
site = {"name": "Python教程", "url": "HdhCmsTestpy.cn"}
print("网站名:{name}, 地址 {url}".format(**site))
# 通过列表索引设置参数
my_list = ['Python教程', 'HdhCmsTestpy.cn']
print("网站名:{0[0]}, 地址 {0[1]}".format(my_list)) # "0" 是必须的
运行结果:
网站名:Python教程, 地址 HdhCmsTestpy.cn
网站名:Python教程, 地址 HdhCmsTestpy.cn
网站名:Python教程, 地址 HdhCmsTestpy.cn 例三:也可以向 str.format() 传入对象:
class AssignValue(object):
def __init__(self, value):
self.value = value
my_value = AssignValue(6)
print('value 为: {0.value}'.format(my_value)) # "0" 是可选的 输出 结果为:
value 为: 6
例四:下表展示了 str.format() 格式化数字的多种方法
print("{:.2f}".format(3.1415926));
3.14 def data_to_str(d):
'''
:param d: 日期字典
:return: str 格式化后的日期
'''
s1='{} {:>02} {:>02}'.format(t['year'],t['month'],t['day'])
s2='{} {:>02} {:>02}'.format(t['hour'],t['minute'],t['second'])
print(s1,s2)
print('-'.join(s1.split()),end=' ')
print(':'.join(s2.split()))
return 0
t={'year':'2013','month':'9','day':'30','hour':'16','minute':'45','second':'2'}
print(data_to_str(t)) 运行结果:
2013 09 30 16 45 02 2013-09-30 16:45:02
相关推荐:《Python教程》
以上就是python的format怎么用的详细内容,更多请关注Gxl网其它相关文章!
查看更多关于python的format怎么用的详细内容...
声明:本文来自网络,不代表【好得很程序员自学网】立场,转载请注明出处:http://www.haodehen.cn/did79371