2013-12-11 33 views
3
>>> foo = 1 
>>> type(foo) 
<type 'int'> 
>>> type(str(foo)) 
<type 'str'> 
>>> type(`foo`) 
<type 'str'> 

将整数转换为字符串的更多Pythonic方法是哪一种?我一直使用第一种方法,但我现在发现第二种方法更具可读性。有实际的区别吗?将整数转换为字符串的pythonic方式

回答

10

String conversions using backticks是对值repr()的简写符号。为整数,所产生的str()repr()输出恰好是相同的,但它是不相同的操作:

>>> example = 'bar' 
>>> str(example) 
'bar' 
>>> repr(example) 
"'bar'" 
>>> `example` 
"'bar'" 

的反引号语法是removed from Python 3;我不会使用它,因为清晰的str()repr()呼叫在其意图中更加清晰。

请注意,您有更多选项将整数转换为字符串;您可以使用str.format()old style string formatting operations整数插值到一个较大的字符串:

>>> print 'Hello world! The answer is, as always, {}'.format(42) 
Hello world! The answer is, as always, 42 

这比使用字符串连接更加强大。

+0

为“调用repr()”位的简写符号而欢呼。每天学些新东西。 – Ayrx