repr() 函數將對象轉化為供解釋器讀取的形式。
語法:
repr(object)
返回一個對象的 string 格式。
tuple1 = (1,2,3)
print(type(repr((tuple1)))) # 運行結果:<class 'str'>
repr(str)與在字符串前加上“r”或“R”的原理有點相似,但又不一樣。
str1 = 'Hello \n World!'
print(str1)
"""
運行結果:
Hello World!
"""
print(repr(str1)) # 運行結果:'Hello \n World!'str2 = r'Hello \n World!'
print(str2) # 運行結果:Hello \n World!
在字符串前面加上“r”或“R”,是直接作用在字符串常量上。?
函數repr(str)是直接作用在字符串變量上。?
在使用repr(str)函數時要注意:輸入的字符串參數必須是一個正常的字符串。如果對一個原字符串(raw string)進行repr轉化,則會使反斜杠變得更多。
str1 = r'Hello \n World!'
print(repr(str1)) # 運行結果:'Hello \\n World!'