python:基础格式化输出之format用法

format用法

 相对基本格式化输出采用‘%’的方法,format()功能更强大,该函数把字符串当成一个模板,通过传入的参数进行格式化,并且使用大括号‘{}’作为特殊字符代替‘%’

使用方法由两种:b.format(a)和format(a,b)。

1、基本用法

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

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

  (3)带关键字,即“{a}”、“{tom}”

 

>>> print('{} {}'.format('hello','world'))  # 不带字段
hello world
>>> print('{0} {1}'.format('hello','world')) # 带数字编号
hello world
>>> print('{0} {1} {0}'.format('hello','world')) # 打乱顺序
hello world hello
>>> print('{1} {1} {0}'.format('hello','world'))
world world hello
>>> print('{a} {tom} {a}'.format(tom='hello',a='world')) # 带关键字
world hello world
posted @ 2021-07-08 17:01  Tester-**  阅读(362)  评论(0编辑  收藏  举报