python下str()与repr区别

244 阅读1分钟

描述

在 Python 中要将某一类型的变量或者常量转换为字符串对象通常有两种方法,即 str() 或者 repr()

from datetime import dat
                        
a = 10                  
print(str(a))           
print(repr(a))          
print(type(str(a)))     
print(type(repr(a)))    
                        
s='123'                 
print(str(s))           
print(repr(s))          
print(type(str(s)))     
print(type(repr(s)))    
                        
now = datetime.now()    
print(str(now))         
print(repr(now))        
                     
# 输出结果
10
10
<class 'str'>
<class 'str'>
123
'123'
<class 'str'>
<class 'str'>
2020-03-16 18:31:56.177642
datetime.datetime(2020, 3, 16, 18, 31, 56, 177642)

造成这两种输出形式不同的原因在于:

print 语句结合 str() 函数实际上是调用了对象的 str 方法来输出结果

而 print 结合 repr() 实际上是调用对象的 repr 方法输出结果。

print('123'.__str__())   # 123
print('123'.__repr__())  # '123'

源码解读

def repr(obj): # real signature unknown; restored from __doc__
    """
    Return the canonical string representation of the object.
    
    For many object types, including most builtins, eval(repr(obj)) == obj.
    """
    pass

def __init__(self, value='', encoding=None, errors='strict'): # known special case of str.__init__
    """
    str(object='') -> str
    str(bytes_or_buffer[, encoding[, errors]]) -> str
    
    Create a new string object from the given object. If encoding or
    errors is specified, then the object must expose a data buffer
    that will be decoded using the given encoding and error handler.
    Otherwise, returns the result of object.__str__() (if defined)
    or repr(object).
    encoding defaults to sys.getdefaultencoding().
    errors defaults to 'strict'.
    # (copied from class doc)
    """
    pass

案例解析

# 数据中插入的数据需要 ''
action="insert into stock(code,name,b_price,s_price,num,rate,profit) values (%f,%s,%f,%f,%f,%f,%f)" % (s5,repr(s6),s1,s2,s3,s4,sum)

其他

# 在字符串双引号""中使用单引号'
cmd = "ps -ef|grep libreoffice | awk '{print $2}' | xargs kill -9"
os.system(cmd)