python 内置函数format

Python2.6 开始,新增了一种格式化字符串的函数 str.format(),它增强了字符串格式化的功能。

基本语法是通过 {} 和 : 来代替以前的 % 。

format 函数可以接受不限个参数,位置可以不按顺序。

代码如下图:

#coding="utf-8"
print("{} {}".format("hello", "world") )
print("{0} {1}".format("hello", "world"))
print("{1} {0} {1}".format("hello", "world"))
print("网站名:{name}, 地址 {url}".format(name="菜鸟教程", url="www.runoob.com"))
#set the value by dict
site = {"name": "菜鸟教程", "url": "www.runoob.com"}
print("网站名:{name}, 地址 {url}".format(**site))

运行结果如下:

F:devpythonpython.exe F:/pyCharm/practice/config_dir/zip_demo.py
hello world
hello world
world hello world
网站名:菜鸟教程, 地址 www.runoob.com
网站名:菜鸟教程, 地址 www.runoob.com

Process finished with exit code 0

原文地址:https://www.cnblogs.com/linwenbin/p/10384609.html