Python |三种格式化输出

一、格式化输出

1、字符串的格式化输出目前有三种方式:
% 方式:python2.x 及以上版本都支持;
str.format()方式:python2.7以上版本都支持;
f-string方式:python3.6版本及以上推荐使用。

二、格式化输出的基本语法

1、% 百分号方式
注:%s 的个数代表后边的字符串的个数

>>> test = "I am %s"
>>> msg = test % ("a boy")
>>> msg
'I am a boy'
>>> test1 = "I am %s,%s"
>>> msg = test1 % ("a boy","tall boy")
>>> msg
'I am a boy,tall boy'
>>> 

2、str.format()方式

>>> test = "she is {}"
>>> test.format("woman")
'she is woman'
>>> test = "she is {},{}"
>>> test.format("woman","age is 19")
'she is woman,age is 19'
>>> li = ["woman","age is 19"]
>>> test.format(*li)
'she is woman,age is 19'
>>> info = {
     "name":"mike","age":18}
>>> msg.format(**info)
'I am a boy,tall boy'
>>> test = "I am {name},{age}"
>>> test.format(age=18,name="shark")
'I am shark,18'

3、f-strings方式

>>> user = "mike"
>>> ip = "192.168.43.132"
>>> pwd = "xiaoshuaige"
>>> test_mysql = f"mysql -u{user} -p{pwd} -h{ip}"
>>> test_mysql
'mysql -umike -pxiaoshuaige -h192.168.43.132'
>>> 

你可能感兴趣的:(#,Python,python)