相关疑难解决方法(0)

__str__和__repr__之间的区别?

之间有什么区别__str____repr____str__

python repr magic-methods

2545
推荐指数
21
解决办法
61万
查看次数

使用__str__方法连接python对象列表

我已经看过这个关于在Python中表示字符串的问题,但我的问题略有不同.

这是代码:

>>> class WeirdThing(object):
...     def __init__(self):
...         self.me = time.time()
...     def __str__(self):
...         return "%s" % self.me
...     def __repr__(self):
...         return ";%s;" % self.me
... 
>>> weird_list = [WeirdThing(), WeirdThing(), WeirdThing()]
>>> print weird_list
[;1302217717.89;, ;1302217717.89;, ;1302217717.89;]
>>> "\n".join(weird_list)
Traceback (most recent call last):
  File "<console>", line 1, in <module>
TypeError: sequence item 0: expected string, WeirdThing found
Run Code Online (Sandbox Code Playgroud)

我意识到这有效:

>>> "\n".join(str(wi) for wi in weird_list)
'1302217717.89\n1302217717.89\n1302217717.89'
>>> 
Run Code Online (Sandbox Code Playgroud)

每次我想要将对象连接在一起时,避免这样做仍然会很好.这根本不可能吗?

python string

7
推荐指数
1
解决办法
4940
查看次数

标签 统计

python ×2

magic-methods ×1

repr ×1

string ×1