python里{!r}的格式控制

今天是学习Python第一次接触{!r}控制输出,是在学习finditer()函数时看到的:https://blog.csdn.net/caimouse/article/details/78169027

经过查找资料学习,以下为学习收获:(包含{!r}和%r)

import re

pattern = re.compile('\d+')
text='one1two2three3four4'

for match in re.finditer(pattern, text):
    s = match.start()
    e = match.end()
    print('Found {!r} at {:d}:{:d}'.format(
        text[s:e], s, e))

输出:
Found ‘1’ at 3:4
Found ‘2’ at 7:8
Found ‘3’ at 13:14
Found ‘4’ at 18:19

发现{!r}对应输出的是一个字符串!
以下用例子来简单讲解以下{!r}:

'hello,{!r},this is {}!'.format('world','Ashley')

输出:
“hello,‘world’,this is Ashley!”
对比用{!r}和{}的区别,发现前者输出的字符包含单引号,而后者则无。
与{!r}类似的还有%r:

'hello,%r'%'world'

输出:
“hello,‘world’”
同样地,输出的world前后有单引号包围,但是与{!r}有所不同的是:
{!r}与format()配合使用,而%r与%配合使用,二者不可以混合使用,否则会报错!

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值