小时? 发表于 2018-8-15 12:32:34

python问题笔记之str()和repr()的区别

  print(str("hello"))
  输出为
  hello
  print (repr("hello"))
  输出为
  'hello'
  这两者之间有什么区别呢?
  str()一般是将数值转成字符串。
  repr()是将一个对象转成字符串显示,注意只是显示用,有些对象转成字符串没有直接的意思。如list,dict使用str()是无效的,但使用repr可以,这是为了看它们都有哪些值,为了显示之用。
  Some examples:
  >>> s = 'Hello, world.'
  >>> str(s)
  'Hello, world.'
  >>> repr(s)
  "'Hello, world.'"
  >>> str(0.1)
  '0.1'
  >>> repr(0.1)
  '0.10000000000000001'
  >>> x = 10 * 3.25
  >>> y = 200 * 200
  >>> s = 'The value of x is ' + repr(x) + ', and y is ' + repr(y) + '...'
  >>> print s
  The value of x is 32.5, and y is 40000...
  >>> # The repr() of a string adds string quotes and backslashes:
  ... hello = 'hello, world\n'
  >>> hellos = repr(hello)
  >>> print hellos
  'hello, world\n'
  >>> # The argument to repr() may be any Python object:
  ... repr((x, y, ('spam', 'eggs')))
  "(32.5, 40000, ('spam', 'eggs'))"
  >>> # reverse quotes are convenient in interactive sessions:
  ... `x, y, ('spam', 'eggs')`
  "(32.5, 40000, ('spam', 'eggs'))"
  提示技巧:在提示符后直接输入一个变量名print (s),结果跟print(repr(s))是一样的。
  或者直接输入变量名字:s、 (s) 、x、 y都可以显示它的值的 。
  但是(区别是)直接输入是(返回)它的值,用print语句打印是(打印)它的值,这两者之间是有差别的。
页: [1]
查看完整版本: python问题笔记之str()和repr()的区别