Python中的值转字符串

    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.


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值