python 字符format格式化应用

Posted mango_lee

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python 字符format格式化应用相关的知识,希望对你有一定的参考价值。

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格式化应用的主要内容,如果未能解决你的问题,请参考以下文章

python中的格式化输出and format()应用

Python之路--Python中应该使用%还是format来格式化字符串?

Python中应该使用%还是format来格式化字符串?

Python 中格式化字符串 % 和 format 两种方法之间的区别

python 字符串的格式化

Python 的字符串 .format() 可以对不受信任的格式字符串安全吗?