今天是学习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与%配合使用,二者不可以混合使用,否则会报错!