现在的位置: 首页 > 综合 > 正文

Python中的值转字符串

2013年10月10日 ⁄ 综合 ⁄ 共 1480字 ⁄ 字号 评论关闭

    What is actually going on here is that values are converted to strings through two different mechanisms. You can use both mechanisms yourself, through the functions str and repr. str simply converts a value into a string in
some reasonable fashion that will probably be understood

by a user, for example.11 repr creates a string that is a representation of the value as a legal Python expression. 

Here are a few examples:

>>> print repr("Hello, world!")
'Hello, world!'
>>> print repr(10000L)
10000L
>>> print str("Hello, world!")
Hello, world!
>>> print str(10000L)
10000

A synonym for repr(x) is `x` (here, you use backticks, not single quotes). This can be useful

when you want to print out a sentence containing a number:

>>> temp = 42
>>> print "The temperature is " + temp
Traceback (most recent call last):
File "<pyshell#61>", line 1, in ?
print "The temperature is " + temp
TypeError: cannot add type "int" to string
>>> print "The temperature is " + `temp`
The temperature is 42
>>>print "the temp is : " + repr(temp)

note : Backticks(反引号,即带有“~”的那个按键) are removed in Python 3.0, so even though you may find backticks in old code, you should probably stick with repr yourself.

    The first print statement doesn’t work because you can’t add a string to a number. The second one, however, works because I have converted temp to the string "42" by using the backticks.(I could have just as well used repr, which means the same thing, but
may be a bit clearer.Actually, in this case, I could also have used str. Don’t worry too much about this right now.)In short, str, repr, and backticks are three ways of converting a Python value to a string.
The function str makes it look good, while repr (and the backticks) tries to make the resulting string a legal Python expression.

抱歉!评论已关闭.