python格式化输出
一、 简单介绍
字符串的格式化输出目前有三种方式
%
方式(陈旧) python2.x及以上 都支持str.format()
方式 python2.7及以上都支持f-string
方式 (Python3.6 及以上推荐使用)
二、常用操作
1. % 百分号方式
>>> tpl = "i am %s"
>>> msg = tpl % "shanhai"
>>> msg
'i am shanhai'
>>>
>>> tpl = "i am %s, %s"
>>> msg = tpl % ("shanhai", 18)
>>> msg
'i am shanhai, 18
>>>
>>> user = "shanhai"
>>> age = 18
>>> msg = "i am %s, %s" % (user, age)
>>> msg
'i am shanhai, 18
2. str.format() 方式
>>> msg = "I am {}"
>>> msg.format("shanhai")
'I am shanhai'
>>>
>>> msg = "I am {}, {}"
>>> msg.format("shanhai", 18)
'I am shanhai, 18'
>>>
>>> li = ["shanhai", 18]
>>> msg.format(*li)
'I am shanhai, 18'
>>>
>>> msg = "I am {name}, {age}"
>>> msg.format(age=18, name="shanhai")
'I am shanhai, 18'
>>>
>>> info = {"name": "shanhai", "age": 18}
>>> msg.format(**info)
'I am shanhai, 18'
>>>
3. f-strings 方式
需要先定义好变量,变量名必须和字符串中大括号内的变量名一致
>>> ip="192.168.1.100"
>>> user="admin"
>>> pwd="Shanhai123!"
>>> conn_mysql = f"mysql -u{user} -p{pwd} -h {ip}"
>>> conn_mysql
'mysql -uadmin -pShanhai123! -h 192.168.1.100'