Home  >  Article  >  Backend Development  >  python convert string using str & repr

python convert string using str & repr

WBOY
WBOYOriginal
2016-12-05 13:27:141460browse

可能比较 low 还是记录一下:

str 和 repr的使用过程

  1. str 是一个类型 (int, long 类似), 同样她也可以作为一个工厂方法 实例一个 string
  2. repr 是python 内置的函数, 用于保留一个 打印值在python 代码片段里的真实状态

好,以上全是废话

>>> a = 1
>>> a + ""
---------------------------------------------------------------------------
TypeError
Traceback (most recent call last)
<ipython-input-5-ebf3ab7f3a34> in <module>()
----> 1 a + ""

TypeError: unsupported operand type(s) for +: 'int' and 'str'
>>> a = 1
>>> repr(a) + ""

可以看到, 我们可以通过使用 str 和 repr 来转换字符串

但是,str 只能提供一个 元string来做转换, 不可以是一个变量(她不具备执行变量的能力)

repr 是一个函数, 所以实际上是传参, 可以是变量和string

好多人都知道str()能把123数字转成字符串,python里的str()甚至还能把列表、字典等对象转成字符串。这都好理解,可是一旦把str()和repr()放在一起,大家就全都不淡定了-_-!

来看一段代码,仍是在IDLE里交互:

  >>> str('hello')
  'hello'
  >>> repr('hello')
  "'hello'"

  >>> str('你好')
  '\xc4\xe3\xba\xc3'
  >>> repr('你好')
  "'\\xc4\\xe3\\xba\\xc3'"

先看前两句:英文的'hello'在str()后仍是'hello',可是在repr()后就变成了"'hello'"。这就说明,str()返回的就是字符串本身,而repr()虽然返回的也是字符串,但它是一个标准字符串,官方解释比较绕,我来解释下吧。repr是representation及描述的意思,不是对人的描述,而是对python机器的描述,也就是它会将某物返回一个它在python中的描述。说人话:repr(obj)告诉我们obj这个变量在背地里是什么样子,在背地里是怎么被python处理被python"玩弄"的。

在python里,我们总会被眼睛欺骗。编辑器里显示的东西,并不总是它原本的面貌。python为了方便,总是表面上一套,背地里又一套。

再来理解后两句:中文的'你好'在str()后变成了编码'\xc4\xe3\xba\xc3',在repr()后变成了"'\xc4\xe3\xba\xc3'"。`都加上了转移符变成\,相当于把字符串中的内容都“标准化”了。至于'变成"`只是为了说明repr()返回的是一个经过处理的新字符串。

print后的str()和repr()

来看代码:

  >>> print str('你好')
  你好
  >>> print repr('你好')
  '\xc4\xe3\xba\xc3'

之前str('你好')显示的是'\xc4\xe3\xba\xc3',而一经过print,就变成了正确的'你好'。上面说过了,命令行里直接输入一个变量,显示的是它在python后台存储的数据;而用print出来的东西,会显出出尽量友好、让人能看懂的东西。
理解了这个,对print这两个结果的不同,也就全然理解了。然后也就放弃print作为考据的心了。

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn