简体   繁体   English

Python为什么变量和return显示与print变量的差值?

[英]Python why variable and return show difference value from print variable?

>>> pkt = sniff(count=2,filter="tcp")
>>> raw  = pkt[1].sprintf('%Padding.load%')
>>> raw
"'\\x04\\x00\\x00\\x00\\x00\\x00\\x00\\x00g\\xc4|\\x00\\x00\\x00\\x00\\x00'"


>>> print raw
'\x04\x00\x00\x00\x00\x00\x00\x00g\xc4|\x00\x00\x00\x00\x00'

Raw yield different output when use print 使用打印时原始产量不同

One is the repr() representation of the string, the other the printed string. 一个是字符串的repr()表示形式,另一个是打印的字符串。 The representation you can paste back into the interpreter to make the same string again. 您可以将表示形式粘贴回解释器中,以再次生成相同的字符串。

The Python interactive prompt always uses repr() when echoing variables, print always uses the str() string representation. 当交互变量时,Python交互式提示始终使用repr() ,而print始终使用str()字符串表示形式。

They are otherwise the same. 它们在其他方面是相同的。 Try print repr(raw) for comparison: 尝试print repr(raw)进行比较:

>>> "'\\x04\\x00\\x00\\x00\\x00\\x00\\x00\\x00g\\xc4|\\x00\\x00\\x00\\x00\\x00'"
"'\\x04\\x00\\x00\\x00\\x00\\x00\\x00\\x00g\\xc4|\\x00\\x00\\x00\\x00\\x00'"
>>> print "'\\x04\\x00\\x00\\x00\\x00\\x00\\x00\\x00g\\xc4|\\x00\\x00\\x00\\x00\\x00'"
'\x04\x00\x00\x00\x00\x00\x00\x00g\xc4|\x00\x00\x00\x00\x00'
>>> print repr("'\\x04\\x00\\x00\\x00\\x00\\x00\\x00\\x00g\\xc4|\\x00\\x00\\x00\\x00\\x00'")
"'\\x04\\x00\\x00\\x00\\x00\\x00\\x00\\x00g\\xc4|\\x00\\x00\\x00\\x00\\x00'"

__str__ and __repr__ built in methods of a class can return whatever string values they want. 类的内置方法中的__str____repr__可以返回所需的任何字符串值。 Some classes will simply use a str() for their repr. 一些类将简单地使用str()作为它们的代表。

class AClass(object):

   def __str__(self):
      return "aclass"

   def __repr__(self):
      return str(self)

class AClass2(AClass):

   def __repr__(self):
      return "<something else>"

In [2]: aclass = AC
AClass   AClass2  

In [2]: aclass = AClass()

In [3]: print aclass
aclass

In [4]: aclass
Out[4]: aclass

In [5]: aclass2 = AClass2()

In [6]: print aclass2
aclass

In [7]: aclass2
Out[7]: <something else>

In [8]: repr(aclass2)
Out[8]: '<something else>'

In [9]: repr(aclass)
Out[9]: 'aclass'

repr is simply meant to show a "label" of the class, such as when you print a list that contains a bunch of this instance...how it should look. repr只是为了显示该类的“标签”,例如,当您打印包含大量此类实例的列表时,它应该看起来如何。

str is how to convert the instance into a proper string value to be used in operations. str是如何将实例转换为适当的字符串值以用于操作中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM