python中的str()和repr()

str()repr()都被用来获得一个对象的字符串表示。

1. str和repr不同

看个例子

str():

s = 'Hello, Geeks.'
print str(s)
print str(2.0/11.0)

output:

Hello, Geeks.
0.181818181818

repr():

s = 'Hello, Geeks.'
print repr(s)
print repr(2.0/11.0)

output:

'Hello, Geeks.'
0.18181818181818182

上面的例子中,repr()返回的字符串多了一对引号,返回的float类型精度也更高。

str和repr的区别

  1. str被用作为终端用户创建输出;而repr()被主要用来开发调试。repr的目的是清晰;str的目的是可读。
  2. repr()用来获得一个对象的正式(offical)字符串;str()用来获得一个对象的非正式(informal)字符串。
  3. 在对象内部,str()内建函数使用__str__()来展示对象的字符串表示;repr()内建函数使用__repr__()来展示对象。

再看个例子

code:

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)

2. 自定义类中使用它们

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) 


Ref

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值