python格式化输出

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'
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值