看代码的时候一头雾水,不清楚什么情况下使用:

print "It write: %s." % qprint "It write: %r." % q

这二者有什么区别吗?


慕桂英4014372
浏览 107回答 2
2回答

潇湘沐

%r是repr%s就是str比如\x27是单引号>>>&nbsp;print&nbsp;'%r'%'\x27'&nbsp;#&nbsp;带括号的单引号"'"&nbsp; >>>&nbsp;print&nbsp;'%s'%'\x27'&nbsp;#&nbsp;纯单引号'>>>&nbsp;class&nbsp;Example(object):&nbsp;...&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;__repr__&nbsp;=&nbsp;lambda&nbsp;cls:&nbsp;'<Demo>(repr)'...&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;__str__&nbsp;&nbsp;=&nbsp;lambda&nbsp;cls:&nbsp;'<Demo>(str)'...&nbsp;>>>&nbsp;example&nbsp;=&nbsp;Example()>>>&nbsp;print&nbsp;'%s'%example<Demo>(str)>>>&nbsp;print&nbsp;'%r'%example<Demo>(repr)

Cats萌萌

s意义是字符串r意义是使用repr,而不是str%r 用来做 debug 比较好,因为它会显示变量的原始数据(raw data),而其它的符号则是用来向用户显示输出的。在《笨办法学习Python(第三版)》中有详细说明比如>>>&nbsp;print&nbsp;'%s,&nbsp;%s'%('one',&nbsp;'two') one,&nbsp;two >>>&nbsp;print&nbsp;'%r,&nbsp;%r'%('one',&nbsp;'two')'one',&nbsp;'two'个人习惯还是喜欢用format方法
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python