Python repr() 或str() 函数, 反引号
2014-08-28 18:17
441 查看
Python 有办法将任意值转为字符串:将它传入repr() 或str() 函数。
函数str() 用于将值转化为适于人阅读的形式,而repr() 转化为供解释器读取的形式(如果没有等价的
语法,则会发生SyntaxError 异常) 某对象没有适于人阅读的解释形式的话, str() 会返回与repr()
等同的值。很多类型,诸如数值或链表、字典这样的结构,针对各函数都有着统一的解读方式。字符串和
浮点数,有着独特的解读方式。
Some examples:
下面有些例子
>>> s
= 'Hello, world.'
>>> str(s)
'Hello, world.'
>>> repr(s)
"'Hello, world.'"
>>> str(1.0/7.0)
'0.142857142857'
>>> repr(1.0/7.0)
'0.14285714285714285'
>>> 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'))"
repr函数用来取得对象的规范字符串表示。反引号(也称转换符)可以完成相同的功能。注
意,在大多数时候有eval(repr(object)) == object。
>>> i
= []
>>> i.append('item')
>>> `i`
"['item']"
>>> repr(i)
"['item']"
基本上,repr函数和反引号用来获取对象的可打印的表示形式。你可以通过定义类的
__repr__方法来控制你的对象在被repr函数调用的时候返回的内容。
转载:http://blog.chinaunix.net/uid-21961132-id-3081300.html
函数str() 用于将值转化为适于人阅读的形式,而repr() 转化为供解释器读取的形式(如果没有等价的
语法,则会发生SyntaxError 异常) 某对象没有适于人阅读的解释形式的话, str() 会返回与repr()
等同的值。很多类型,诸如数值或链表、字典这样的结构,针对各函数都有着统一的解读方式。字符串和
浮点数,有着独特的解读方式。
Some examples:
下面有些例子
>>> s
= 'Hello, world.'
>>> str(s)
'Hello, world.'
>>> repr(s)
"'Hello, world.'"
>>> str(1.0/7.0)
'0.142857142857'
>>> repr(1.0/7.0)
'0.14285714285714285'
>>> 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'))"
repr函数用来取得对象的规范字符串表示。反引号(也称转换符)可以完成相同的功能。注
意,在大多数时候有eval(repr(object)) == object。
>>> i
= []
>>> i.append('item')
>>> `i`
"['item']"
>>> repr(i)
"['item']"
基本上,repr函数和反引号用来获取对象的可打印的表示形式。你可以通过定义类的
__repr__方法来控制你的对象在被repr函数调用的时候返回的内容。
转载:http://blog.chinaunix.net/uid-21961132-id-3081300.html
相关文章推荐
- Python内建函数str()和repr()
- python 内建函数 str() 和 repr() 的区别
- Python菜鸟晋级03----repr() 与str() 函数的区别
- python 内建函数 str() 和 repr() 的区别
- python 内建函数 str() 和 repr() 的区别
- Python repr() 函数和str() 函数
- python repr、str、反引号值转化为字符串区别
- Python repr() 或str() 函数
- Python repr str 函数
- Python repr() 或str() 函数
- Python repr() 或str() 函数
- Python内建函数str,repr解析
- Python中str()和repr()函数的区别
- Python repr() 或str() 函数, 反引号 分类: python 2013-05-30 10:47 306人阅读 评论(0) 收藏
- python的class的__str__()和__repr__()函数
- Python repr() 或str() 函数(转)
- Python repr() 或str() 函数
- Python repr() 或str() 函数
- Python repr() 或str() 函数
- 关于python的str()和repr()函数