首页 > 编程语言 > 详细

python 字符format格式化应用

时间:2018-10-15 22:35:47      阅读:145      评论:0      收藏:0      [点我收藏+]

format格式化字符串,将字符串以某种格式化形式输出,基本形式是"***{}***{}***".format(col1,col2)。其中format有两种指定形式,一种是按照index,一种是按照名称。

按照index进行赋值:

>>>"{} {}".format("hello", "world")    # 不设置指定位置,按默认顺序
hello world
 
>>> "{0} {1}".format("hello", "world")  # 设置指定位置
hello world
 
>>> "{1} {0} {1}".format("hello", "world")  # 设置指定位置
world hello world

按照名称进行赋值:

#!/usr/bin/python
# -*- coding: UTF-8 -*-
 
print("网站名:{name}, 地址 {url}".format(name="菜鸟教程", url="www.runoob.com"))
 
# 通过字典设置参数
site = {"name": "菜鸟教程", "url": "www.runoob.com"}
print("网站名:{name}, 地址 {url}".format(**site))
 
# 通过列表索引设置参数
my_list = [菜鸟教程, www.runoob.com]
print("网站名:{0[0]}, 地址 {0[1]}".format(my_list))  # "0" 是必须的

另外是对数字按照某种格式显示

http://www.runoob.com/python/att-string-format.html

python 字符format格式化应用

原文:https://www.cnblogs.com/mango-lee/p/9794867.html

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