2012-12-02 22 views
9

我的Python版本是:在Python原始字符串的情况下

~$ python --version 
Python 2.6.6 

我尝试在Python下(我想全部显示):

1:\用作转义序列

>>> str('Let\'s Python')  
"Let's Python" 

2:\作为转义序列使用

>>> 'Let\'s Python'    
"Let's Python" 

3:str()和打印为值不键入

>>> print 'Let\'s Python'  
Let's Python 

4:其Python中的原始字符串

>>> repr('Let\'s Python')  
'"Let\'s Python"' 

[QUESTION]

5:Python原始字符串

>>> print r'Let\'s Python'  
Let\'s Python 

6:这一点,我不明白如下:

>>> r'Let\'s Python'    
"Let\\'s Python" 

>>> r'\\' 
'\\\\' 

为什么\\?为什么输出在56有区别?
rrepr()是否相同?
也请解释关于stringraw strings的内部表示方式相同或不同。

+0

@MartijnPieters:谢谢! –

回答

10

您在将原始字符串文字r''与字符串表示混淆在一起。有一个很大的不同。 repr()r''都是而不是是同样的事情。

r''原始字符串文字产生一个字符串就像一个正常的字符串文字一样,除了它如何处理转义码。生成的结果仍然是一个python字符串。

>>> r'String with \n escape ignored' 
'String with \\n escape ignored' 
>>> 'String with \\n escape ignored' 
'String with \\n escape ignored' 

如果不使用r''原始字符串字面我只好原路斜线逃吧,否则会被解释为:您可以使用原始字符串字面或普通字符串字面量产生相同的字符串换行符。在使用r''语法时,我不必转义它,因为它根本不解释转义代码,如\n。所述输出,所得Python字符串,是完全一样的:

>>> r'String with \n escape ignored' == 'String with \\n escape ignored' 
True 

解释器使用repr()呼应这些值反馈给我们;蟒值的表示产生:

>>> print 'String' 
String 
>>> print repr('String') 
'String' 
>>> 'String' 
'String' 
>>> repr('String') 
"'String'" 

通知的repr()结果如何包括引号。当我们仅回显一个字符串的repr()时,结果是本身一个字符串,所以它有两个引号集。其他"引号标记repr()的结果的开始和结束,并且在内包含,即Python字符串String的字符串表示形式。

所以r''产生的语法 python字符串,repr()是产生表示python值的字符串的方法。 repr()也适用于其他蟒值:

>>> print repr(1) 
1 
>>> repr(1) 
'1' 

1整数表示为一个字符串'1'(字符1在一个字符串)。

+0

Thanks Martijn!...尽管我还是不明白为什么>>> print r'string with \ n escape ignored'' print'string with \ n escape ignored' ... single'\', –

+0

@GrijeshChauhan:Now尝试没有'r'(不要改变别的)。 '\ n'成为换行符。 –

+1

另一件显示不同之处的是:'len(r'\ n')'与'len('\ n')'。第一个是*两个*字符,一个''''''反斜杠和'n',另一个是*一个*字符,一个换行符。 –

相关问题