[Python3]format字符串格式化输出

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

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

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

# _author_:"wyq"
# date: 2018-7-18

print('{} {}'.format('hello', 'world'))
hello world

print('{0} {1}'.format('hello', 'world'))
hello world

print('{0} {1} {0}'.format('hello', 'world'))
hello world hello

# 通过字典设置参数
dic = {'name': 'wyq', 'age': 26}
print('姓名是:{name} , 年龄是:{age}'.format(**dic))
姓名是:wyq , 年龄是:26

# 通过列表索引设置参数
li = ['wyq', 26]
li1 = ['xf', 27]
print('姓名是:{0[0]} , 年龄是:{0[1]} ,另一个人是{1[0]}, 年龄 {1[1]}'.format(li, li1))
姓名是:wyq , 年龄是:26 ,另一个人是xf, 年龄 27

猜你喜欢

转载自blog.csdn.net/TynMhxx/article/details/81091743