最新消息:20210816 当前crifan.com域名已被污染,为防止失联,请关注(页面右下角的)公众号

[基本解决]Python中格式化字符串参数%s vs %r

Python crifan 3391浏览 0评论

折腾:

[已解决]Flask中app.logger.debug出错:UnicodeEncodeError ascii codec can’t encode characters in position 59-68 ordinal not in range 128

期间,需要去搞清楚:

到底%s还是%r有何区别

搜:

python string format %s %r

参考:

string – When to use %r instead of %s in Python? – Stack Overflow

PyFormat: Using % and .format() for great good!

%s用str()去转换为对应的字符串

%r用repr()去转换为对应的字符串

对于有些对象,比如数字,那么str()和repr()输出的结果是一样的

但是有些对象,两者输出的结果不同

但是还是没找到问题根本原因

搜:

python str() repr()

Python 中 str 和 repr 的区别 – 技术翻译 – 开源中国社区

Difference between __str__ and __repr__ in Python – Stack Overflow

__repr__的目标是准确性

__str__的目标是可读性

python中str和repr区别 – 风之别鹤 – 51CTO技术博客

repr语法:repr[object]

返回一个可以表示对象的可打印的字符串,首先会生成一个这样的字符串,然后将其传给eval()可以重新生成同样的对象。但是repr所返回的对象更适合于解释器去阅读,可以理解为亲近与python。

str语法:str[objec]

返回一个可以表示对象的友好的可打印的字符串。对于字符串则返回本身,如果没有参数,则返回空字符串。str返回的对象更适合我们人类阅读(可以这么理解),str致力于返回一个可读性比较好的对象,返回的结果通常不会通过eval()去处理。

__repr__ is for developers

__str__ is for customers.

__repr__: representation of python object usually eval will convert it back to that object

__str__: is whatever you think is that object in text form

repr(object)

Return a string containing a printable representation of an object. This is the same value yielded by conversions (reverse quotes). It is sometimes useful to be able to access this operation as an ordinary function. For many types, this function makes an attempt to return a string that would yield an object with the same value when passed to eval(), otherwise the representation is a string enclosed in angle brackets that contains the name of the type of the object together with additional information often including the name and address of the object. A class can control what this function returns for its instances by defining a __repr__() method.

str(object=”)

Return a string containing a nicely printable representation of an object. For strings, this returns the string itself. The difference with repr(object) is that str(object) does not always attempt to return a string that is acceptable to eval(); its goal is to return a printable string. If no argument is given, returns the empty string, ”.

转载请注明:在路上 » [基本解决]Python中格式化字符串参数%s vs %r

发表我的评论
取消评论

表情

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址
82 queries in 0.182 seconds, using 22.06MB memory