是什么区别print,object和repr()?为什么要以不同的格式打印?
见output difference:
>>> x="This is New era"
>>> print x # print in double quote when with print()
This is New era
>>> x # x display in single quote
'This is New era'
>>> x.__repr__() # repr() already contain string
"'This is New era'"
>>> x.__str__() # str() print only in single quote ''
'This is New era'
Run Code Online (Sandbox Code Playgroud) 我正在尝试将控制字符(例如应该删除先前字符的'\ x08\x08)应用于字符串(向后移动,写入空格,向后移动)
例如当我键入python控制台时:
s = "test\x08 \x08"
print s
print repr(s)
Run Code Online (Sandbox Code Playgroud)
我进入我的终端:
tes
'test\x08 \x08'
Run Code Online (Sandbox Code Playgroud)
我正在寻找一个函数,让我们说"函数",它将"应用"控制字符到我的字符串:
v = function("test\x08 \x08")
sys.stdout.write(v)
sys.stdout.write(repr(v))
Run Code Online (Sandbox Code Playgroud)
所以我得到一个"干净",无控制字符的字符串:
tes
tes
Run Code Online (Sandbox Code Playgroud)
我理解在终端中,这部分是由客户端处理的,所以可能有一种方法来获取显示的字符串,使用核心unix函数
echo -e 'test\x08 \x08'
cat file.out # control char are here handled by the client
>> tes
cat -v file.out # which prints the "actual" content of the file
>> test^H ^H
Run Code Online (Sandbox Code Playgroud) 我正在将一个python库从python 2移植到一个代码库(2.6,2.7和3.3+)中的python 2和3.剩下的主要问题是很多测试使用这样的东西:
def test(self):
example = {u'foo': u'bar'}
self.assertEqual(str(example), "{u'foo': u'bar'}")
Run Code Online (Sandbox Code Playgroud)
它在python 2中工作,但在python3中引发异常:
AssertionError: "{'foo': 'bar'}" != "{u'foo': u'bar'}"
Run Code Online (Sandbox Code Playgroud)
除了"测试不同"之外,还有一种处理这些问题的标准方法吗?超载__repr__?
在Lua中是否有与Python的repr()函数相同的函数?换句话说,一个函数使用\ x打印不可打印的字符,其中x是n或b等,如果不是Lua字符串转义字符,则打印\ 000代码.我用谷歌搜索,找不到任何东西.很多关于将非printables放在字符串中的信息,没有关于使用不可打印的字符生成字符串的打印友好版本.
我在这里问这个问题,因为在我的搜索中,这个错误通常与查询有关,而不是ForeignKey赋值.
我得到的错误发生在模型的方法中.这是代码:
class Deal(models.Model):
...model_fields...
def _update_existing_deal(self, deal_dict):
#deal made from deal_dict here, psuedo code below
deal = Deal(deal_dict)
HistoricalDeal().create_historical_deal(deal)
self.price = deal_dict.get('price', self.price)
if self.comment != deal_dict.get['comment']:
self.comment = deal_dict.get('comment', '')
self.set_unit_price()
logger.debug(
'Existing deal, (pk: %d), updated.',
self.pk
)
class HistoricalDeal(models.Model):
deal = models.ForeignKey(Deal)
created_at = models.DateTimeField(auto_now_add=True)
price = models.DecimalField(max_digits=8, decimal_places=2, blank=True,
default=0)
unit_price = models.DecimalField(decimal_places=2, max_digits=6,
null=True, blank=True)
def create_historical_deal(self, deal):
self.deal = deal
self.price = deal.price
self.unit_price = deal.unit_price
self.save()
logger.debug(
'HistoricalDeal created for Deal with …Run Code Online (Sandbox Code Playgroud) class MyClass:
def __init__(self):
self.list_ = []
def __repr__(self):
return '\n'.join(['this','should','all','be','on','separate','lines']) + str([str(list_val) for list_val in self.list_])
myClass = MyClass()
myClass.list_.append(MyClass())
myClass.list_[0].list_.append(MyClass())
print(myClass)
Run Code Online (Sandbox Code Playgroud)
我希望此代码打印:
this
should
all
be
on
separate
lines[this
should
all
be
on
separate
lines[this
should
all
be
on
separate
lines]]
Run Code Online (Sandbox Code Playgroud)
或类似的东西,但它打印
this
should
all
be
on
separate
lines["this\nshould\nall\nbe\non\nseparate\nlines['this\\nshould\\nall\\nbe\\non\\nseparate\\nlines[]']"]
Run Code Online (Sandbox Code Playgroud)
也就是说,当我尝试将一个对象转换为字符串时,它已经在__repr__同一个类的另一个对象的方法中,它会将换行符转换为\n,如果我进一步嵌套它,它会导致\\n,每次我嵌套它都会添加转义序列前的附加反斜杠。
阅读完这个问题后,似乎该__repr__方法认为我实际上想要两个字符\and n,但我不想要:我想要转义序列\n。有什么方法可以覆盖它并强制它将其解释为换行符而不是两个单独的字符?
情况:我是python的新手,目前正在尝试学习绳索,我试图创建一个链接列表类,以帮助更好地理解该语言及其结构。我知道该__repr__函数基本上应该返回与相同的东西,__str__但是我不确定实际的区别是什么。
到目前为止,这是我的课程:
class LinkedList:
class Node:
def __init__(self, val, prior=None, next=None):
self.val = val
self.prior = prior
self.next = next
def __init__(self):
self.head = LinkedList.Node(None)
self.head.prior = self.head.next = self.head
self.length = 0
def __str__(self):
"""Implements `str(self)`. Returns '[]' if the list is empty, else
returns `str(x)` for all values `x` in this list, separated by commas
and enclosed by square brackets. E.g., for a list containing values
1, 2 and 3, returns '[1, 2, 3]'.""" …Run Code Online (Sandbox Code Playgroud) 这是关于Python的repr的一个有趣的奇怪之处:
制表符\x09表示为\t.但是,此约定不适用于null终止符.
为什么\x00表示为\x00,而不是\0?
示例代码:
# Some facts to make sure we are on the same page
>>> '\x31' == '1'
True
>>> '\x09' == '\t'
True
>>> '\x00' == '\0'
True
>>> x = '\x31'
>>> y = '\x09'
>>> z = '\x00'
>>> x
'1' # As Expected
>>> y
'\t' # Okay
>>> z
'\x00' # Inconsistent - why is this not \0
Run Code Online (Sandbox Code Playgroud) 我通常会写一个 a__repr__作为展示如何重新创建实例的方式。例如:
class Component:
def __init__(self, start, end):
self.start = start
self.end = end
def __repr__(self):
return f'{self.__class__.__name__}(start={self.start}, end={self.end})'
Run Code Online (Sandbox Code Playgroud)
是否有一种“标准”的方式来编写__repr__,如果没有,是否有关于如何编写的建议选项/最佳实践,或者它完全是主观的?
我有一个ResourceType继承自namedtupleand的枚举Enum,并且我不会在任何地方重写__str__or __repr__。当我格式化该枚举的实例时,我意外地得到了未修饰的值,而不是repr()或str(). 这怎么可能?被称为什么?
枚举详细信息(简化):
from enum import Enum, auto
from collections import namedtuple
class ResourceType(namedtuple('ResourceType', 'value ext required'), Enum):
RGB = auto(), '.png', True
Run Code Online (Sandbox Code Playgroud)
输出:
>>> repr(ResourceType.RGB)
"<ResourceType.RGB: ResourceType(value=<enum.auto object at 0x7f44b7d48d30>, ext='.png', required=True)>"
>>> str(ResourceType.RGB)
'ResourceType.RGB'
>>> f"{ResourceType.RGB}"
"ResourceType(value=<enum.auto object at 0x7f44b7d48d30>, ext='.png', required=True)"
Run Code Online (Sandbox Code Playgroud)
最后一个值既不是 therepr()也不是 the str(),所以即使namedtuple提供该字符串,为什么它不也提供 str/repr ?