Python格式字符串两种方法比较

编程中跟字符串打交道那是最常见的了,常用的有以下两种方法格式化字符串(% or .format

方法一(%

# 格式的字符串与被格式化的字符串必须一一对应,需格式化的字符串多时,容易搞混
print 'hello %s, you sex is %s.' %('tab', 'boy')
# hello tab, you sex is boy.

print 'hello %s, you sex is %s.' %(boy', 'tab')
# hello boy, you sex is tab.

# 通过字典方式格式化,哪个字符将会格式化到哪里,清晰命了
print 'hello %(name)s, you sex is %(sex)s.' %{'name': 'tab', 'sex': 'boy'}
# hello tab, you sex is boy.

args = {'name': 'tab', 'sex': 'boy'}
print 'hello %(name)s, you sex is %(sex)s.' %(args)
# hello tab, you sex is boy.

方法二(.format)

# 跟方法一第一种方式有点类似的格式化方式
print 'hello {0}, you sex is {1}.'.format('tab', 'boy')
# hello tab, you sex is boy.

# 注意:用字典方式格式化时,指定格式化字符时的位置可以调换
print 'hello {name}, you sex is {sex}.'.format(sex='boy', name='tab)
# hello tab, you sex is boy.

# '**'起到解包的作用 
args = {'name': 'tab', 'sex': 'boy}
print 'hello {name}, you sex is {sex}.'.format(**args)
# hello tab, you sex is boy.

推荐使用 .format 方法进行格式化字符串,一来清晰明了,二来效率更高(format 是字符串 str 内置的方法)。更多关于 .format 的用法文档,用户可在交互模式下(终端输入 python or ipython or bpython ) 输入 help(str.format) 查看

安装 ipython (Ubuntu)

sudo pip install ipython

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值