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:\dev\python\python.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

相关文章:

  • 2022-12-23
  • 2021-07-18
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-09-19
  • 2021-07-04
猜你喜欢
  • 2022-12-23
  • 2022-01-15
  • 2021-10-06
  • 2022-12-23
  • 2021-09-12
  • 2021-08-05
  • 2021-12-14
相关资源
相似解决方案