Python 3 str() 和 repr() 的区别
  TnD0WQEygW8e 2023年11月05日 33 0

python中转换成字符有两种方法:str() 和 repr()
str() 函数:将值转化为适于人阅读的字符串的形式
repr() 函数:将值转化为供解释器读取的字符串形式

 

 字符串示例

str('xxx')   # str转换后还是原来的值
# 'xxx'

repr('xxx')  #repr 转换后是在'xxx'的外层又加了一层引号
# "'xxx'"
str('xxx') == 'xxx'
# True
repr('xxx') == 'xxx'
# False

len(str('xxx'))  # len 求长度
# 3
len(repr('xxx'))  #repr转换后的字符串和str转换后的字符串个数都是不一样的
# 5

 

repr()函数得到的字符串通常可以用来重新获得该对象,repr()的输入对python比较友好。通常情况下obj==eval(repr(obj))这个等式是成立的。

 

将字符串再转换为字符串

>>> repr('abd')  #repr转换后是在'abd'的外层又加了一层引号
"'abd'"
>>> str('abd')   #str转换后还是原来的值
'abd'
>>> str('abd') == 'abd'
True
>>> repr('abd') == 'abd'
False
>>> len(repr('abd'))  #repr转换后的字符串和str转换后的字符串个数都是不一样的
5
>>> len(str('abd'))
3

 

>>> x="hello\n"
>>> x
'hello\n'
>>> print(x)
hello

>>> y=repr(x)
>>> y
"'hello\\n'"
>>> print(y)
'hello\n'
>>>

 


数字示例

将整型转换为字符串

>>> a = 123  #int类型
>>> type(a)
<class 'int'>
>>> str(a)
'123'
>>> type(str(a))
<class 'str'>
>>> print(str(a))  #print输出时会去掉引号,但是仍然是str类型
123
>>> repr(a)
'123'
>>> type(repr(a))
<class 'str'>
>>> print(repr(a))
123
>>> len(repr(a))  #转换后的数据都是'123',所以长度是3
3
>>> len(str(a))   #转换后的数据都是'123',所以长度是3
3

日期示例

import datetime
today = datetime.datetime.now()
print(today)
# 2015-01-31 21:49:25.840500
str(today)
# '2015-01-31 21:49:25.840500'
repr(today)
# 'datetime.datetime(2015, 1, 31, 21, 49, 25, 840500)'

 

 

命令行下print和直接输出的对比

每个类都有默认的__repr__, __str__方法,在命令行下用print 实例时调用的是类的str方法,直接调用的是类的repr方法;在文件模式下没有print的话是不会有输出值的,自己定义一个类A,验证以上结论:

>>> class A():
...     def __repr__(self):
...         return 'repr'
...     def __str__(self):
...         return 'str'
...
>>> a = A()
>>> a    #直接输出调用的是repr方法
repr
>>> print(a)    #print调用的是str方法
str

 

区别

 

This string is intended to be the representation of the object, and suitable for display to the programmer, for instance, while working in interactive interpreter.

A repr() is used in storing the data of pythonic code in such a way that it can be extracted from the code with the library function.

 

Output of __repr__() is in quotes whereas that of __str__() is not. The reason can be traced to official definitions of these functions, which says that __repr__() method and hence (repr() function) computes official string representation of an object. The str() function i.e. __str__() method returns an informal or printable string representation of concerned object, which is used by the print() and format() functions.

 

representation of objects

str(x) gives a readable end-user output of an object, for example, str(x) is used by the command print()

repr(x) is an more exact and informative output (representation) useful for debugging as given by the command line of the interpreter. If __repr__ is not defined, Python gives the type and memory as default output.

For many objects str(x) and repr(x) give (almost) the same output.

 

str() vs repr() in Python


str() and repr() both are used to get a string representation of object.

  1. Example of str():
s = 'Hello, Geeks.'
print (str(s))
print (str(2.0/11.0))

Output:

Hello, Geeks.
0.181818181818

.

  1. Example of repr():
s = 'Hello, Geeks.'
print (repr(s))
print (repr(2.0/11.0))

Output:

'Hello, Geeks.'
0.18181818181818182

From above output, we can see if we print string using repr() function then it prints with a pair of quotes and if we calculate a value we get more precise value than str() function.

Following are differences:

  • str() is used for creating output for end user while repr() is mainly used for debugging and development. repr’s goal is to be unambiguous and str’s is to be readable. For example, if we suspect a float has a small rounding error, repr will show us while str may not.
  • repr() compute the “official” string representation of an object (a representation that has all information about the object) and str() is used to compute the “informal” string representation of an object (a representation that is useful for printing the object).
  • The print statement and str() built-in function uses __str__ to display the string representation of the object while the repr() built-in function uses __repr__ to display the object.

Let understand this by an example:-

import datetime
today = datetime.datetime.now()
 
# Prints readable format for date-time object
print (str(today))
 
# prints the official format of date-time object
print (repr(today))     

Output:

2016-02-22 19:32:04.078030
datetime.datetime(2016, 2, 22, 19, 32, 4, 78030)

str() displays today’s date in a way that the user can understand the date and time.

repr() prints “official” representation of a date-time object (means using the “official” string representation we can reconstruct the object).

How to make them work for our own defined classes?
A user defined class should also have a __repr__ if we need detailed information for debugging. And if we think it would be useful to have a string version for users, we create a __str__ function.

# Python program to demonstrate writing of __repr__ and
# __str__ for user defined classes
 
# A user defined class to represent Complex numbers
class Complex:
 
# Constructor
def __init__(self, real, imag):
self.real = real
self.imag = imag
 
# For call to repr(). Prints object's information
def __repr__(self):
return 'Rational(%s, %s)' % (self.real, self.imag)    
 
# For call to str(). Prints readable form
def __str__(self):
return '%s + i%s' % (self.real, self.imag)    
 
 
# Driver program to test above
t = Complex(10, 20)
 
# Same as "print t"
print (str(t))  
print (repr(t))

Output:

10 + i20
Rational(10, 20)

This article is contributed by Arpit Agarwal. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above

 

 

REF

https://www.geeksforgeeks.org/str-vs-repr-in-python/

https://python.omics.wiki/strings/str-vs-repr

https://www.tutorialspoint.com/str-vs-repr-in-python



【版权声明】本文内容来自摩杜云社区用户原创、第三方投稿、转载,内容版权归原作者所有。本网站的目的在于传递更多信息,不拥有版权,亦不承担相应法律责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@moduyun.com

  1. 分享:
最后一次编辑于 2023年11月08日 0

暂无评论

推荐阅读
TnD0WQEygW8e