“Python中的format 格式化函数”的版本间差异

来自Shiyin's note
跳到导航 跳到搜索
无编辑摘要
第1行: 第1行:
*[https://www.runoob.com/python/att-string-format.html]
*基本语法是通过 {} 和 : 来代替以前的 % 。
*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="菜鸟教程", url="www.runoob.com"))

# 通过字典设置参数
site = {"name": "菜鸟教程", "url": "www.runoob.com"}
print("网站名:{name}, 地址 {url}".format(**site))

==数字格式化==
a=2
a=2
format output
format output
I2.2 02
I2.2 02
I+3.2 +02
I+3.2 +02
F05.1 002.0
支持string和print 命令

a=2.0
format output
F05.1 002.0 (似乎不至此string命令,string的命令出来是‘ 2.0’

2021年12月7日 (二) 08:49的版本

  • [1]
  • 基本语法是通过 {} 和 : 来代替以前的 % 。
  • 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="菜鸟教程", url="www.runoob.com"))

  1. 通过字典设置参数

site = {"name": "菜鸟教程", "url": "www.runoob.com"} print("网站名:{name}, 地址 {url}".format(**site))

数字格式化

a=2
format  output
I2.2         02
I+3.2      +02
F05.1   002.0