一、前言
在我们进行python编码的时候经常需要用到字符串的格式化,下面是常用的几种字符串格式化方式。
二、三种格式化方式
1、%格式化
name = 'xiaoming' age = '10' test = '%s is %s years old' % (name, age) print(test)
output:
xiaoqing is 10 years old
说明:
%s:字符串
%d:十进制整数
%f:浮点数
另外,%也支持字典形式的传递,如下:
test1 = 'Hello %(name)s,id=%(name)s' % {'id': 10, 'name': 'World'} print(test1)
output:
Hello World,id=World
2、str.format()
常规用法
name = 'xiaoming' age = '10' test2 = 'hello, {}, you are {}?'.format(name, age) print(test2)
output:
hello, xiaoming, you are 10?
通过位置访问
name = 'xiaoming' age = '10' test2 = 'hello, {0}, you are {1}?'.format(name, age) print(test2)
output:
hello, xiaoming, you are 10?
通过关键字访问
name = 'xiaoming' age = '10' test3 = 'hello, {name}, you are {age}?'.format(name=name, age=age) print(test3)
out:
hello, xiaoming, you are 10?
3、f格式化
name = 'xiaoming' age = '10' test4 = f'hi, {name}, are you {age}?' print(test4)
output:
hi, xiaoming, are you 10?
备注:第三种字符串格式化是python3.6以上才有的,据说性能是三者中最好的,建议采用这种
如果低于Python3.6,可以通过pip install future-fstrings即可,在相应的py 文件里不需要加import这个库,但是需要头部加上# coding: future_fstrings