总的来说

  • str():将传入的值转换为适合人阅读的字符串形式
  • repr():将传入的值转换为 Python 解释器可读取的字符串形式

 

传入整型

# number
resp = str(1)
print(resp, type(resp), len(resp))
resp = str(1.1)
print(resp, type(resp), len(resp))

resp = repr(1)
print(resp, type(resp), len(resp))
resp = repr(1.1)
print(resp, type(resp), len(resp))


# 输出结果
1 <class 'str'> 1
1.1 <class 'str'> 3
1 <class 'str'> 1
1.1 <class 'str'> 3

 

传入字符串

# string
resp = str("test")
print(resp, type(resp), len(resp))

resp = repr("test")
print(resp, type(resp), len(resp))


# 输出结果
test <class 'str'> 4
'test' <class 'str'> 6

repr() 会在原来的字符串上面加单引号,所以字符串长度会 +2

 

相关文章:

  • 2022-02-09
  • 2022-12-23
  • 2021-11-20
  • 2021-09-29
  • 2021-06-21
  • 2022-12-23
  • 2021-12-28
猜你喜欢
  • 2021-07-31
  • 2022-12-23
  • 2021-05-29
  • 2022-12-23
  • 2022-12-23
  • 2022-01-09
相关资源
相似解决方案