13 | 格式化输出

简单介绍

字符串的格式化输出目前有两种方式

  • % 方式(陈旧) 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


二、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'
>>> 
>>> msg = "I am {name}, {age}"
>>> msg.format(age=18, name="shark")
'I am shark, 18'
>>>
>>> info = {"name": "shark", "age": 18}
>>> msg.format(**info)
'I am shark, 18'
>>>


三、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'

你可能感兴趣的:(13 | 格式化输出)