# 简单介绍
字符串的格式化输出目前有两种方式
%
方式(陈旧) python2.x及以上 都支持str.format()
方式(新式,官方推荐) python2.7及以上都支持f-string
方式 (Python3.6 及以上推荐使用)
# 一、% 百分号方式
>>> tpl = "i am %s"
>>> msg = tpl % "yangge"
>>> msg
'i am yangge'
>>>
>>> tpl = "i am %s, %s"
>>> msg = tpl % ("yangge", 18)
>>> msg
'i am yangge, 18
1
2
3
4
5
6
7
8
9
2
3
4
5
6
7
8
9
# 二、str.format() 方式
>>> msg = "I am {}"
>>> msg.format("yangge")
'I am yangge'
>>>
>>> msg = "I am {}, {}"
>>> msg.format("yangge", 18)
'I am yangge, 18'
>>>
>>> li = ["yangge", 18]
>>> msg.format(*li)
'I am yangge, 18'
>>>
1
2
3
4
5
6
7
8
9
10
11
12
2
3
4
5
6
7
8
9
10
11
12
>>> msg = "I am {name}, {age}"
>>> msg.format(age=18, name="kame")
'I am kame, 18'
>>>
>>> info = {"name": "kame", "age": 18}
>>> msg.format(**info)
'I am kame, 18'
>>>
1
2
3
4
5
6
7
8
2
3
4
5
6
7
8
# 三、f-strings 方式
>>> ip="192.168.1.100"
>>> user="admin"
>>> pwd="QFedu123!"
>>> conn_mysql = f"mysql -u{user} -p{pwd} -h {ip}"
>>> conn_mysql
'mysql -uadmin -pQFedu123! -h 192.168.1.100'
1
2
3
4
5
6
2
3
4
5
6