2011-08-22 47 views
1

當字符串逃過我有以下代碼:的Python:創建一個元組

string = "ad\23e\4x{\s" 
data = (string,) 

當我打印我的元組字符串必須爲每個額外的斜線的數據一共有6個反斜槓凶多吉少。

如何避免多餘的反斜槓?

回答

3

對象data是一個元組。當你打印一個元組時,Python爲每個元素調用repr。如果您想以另一種方式進行格式化,您必須自己進行轉換。

>>> s = "ad\23e\4x{\s" 
>>> d = (s,) 
>>> print d 
('ad\x13e\x04{\\s',) 
>>> print '(%s,)' % (', '.join('"%s"' % _ for _ in d)) 
("adex{\s") 
+0

感謝您的回覆。我想要像這樣在元組中格式化字符串:'code'「ad \ 23e \ 4x {\ s」 'code' –

0

你的意思是這樣的嗎?

In [11]: string = r'ad\23e\4x{\s' 

In [12]: string 
Out[12]: 'ad\\23e\\4x{\\s' 

In [13]: print string 
ad\23e\4x{\s 

In [14]: data=(string,) 

In [15]: data 
Out[15]: ('ad\\23e\\4x{\\s',) 

In [16]: print data 
('ad\\23e\\4x{\\s',) 

In [17]: print data[0] 
ad\23e\4x{\s 
1

這些額外的反斜槓實際上不是在你的字符串,它們是Python的有多麼代表字符串(的想法是,你可以粘貼回一個程序,它會工作)。這是因爲元組的__str__()實現在每個項目上調用repr()。如果你print stringprint data[0]你會在字符串中看到實際上是