初学 Python 笔记【二】格式化输出 format

str.format()

一种格式化字符串的函数,用 {} 和来代替以前的 % 

 

常见用法:

(1)不带编号,即“{}”

  print("{} {}".format("TO", "BE"))

  >>TO BE

 

(2)带数字编号,可调换顺序,即“{1}”、“{2}”

  print("{0}{1}".format("TO", "BE"))

  >>TO BE

  print("{0} {1} {0}".format("TO", "BE"))

  >>TO BE TO

 

(3)带关键字,即“{b}”、“{to}”

  print("{b} {to} {b}".format(to="TO", b="BE")

  >>BE TO BE

 

(4)f”str”,字符串前加f可以达到格式化目的

  name = "tony"

  age = 10

  print(f"{name.capitalize()} is {age:*^10} years old")  # capitalize()将字符串的第一个字母变成大写,其他字母变小写

  >>Tony is ****10**** years old

 

猜你喜欢

转载自www.cnblogs.com/dc2019/p/13164548.html
今日推荐