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

折腾:

期间,需要去搞清楚:

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

搜:

python string format %s %r

参考:

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

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

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

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

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

搜:

python str() repr()

__repr__的目标是准确性

__str__的目标是可读性

“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, ”.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值