2017-02-17 52 views
0

我得到傳入的字符串並且想要以原始格式打印緩衝區(打印雙反斜槓) 如何告訴string.format()這是一個'原始'字符串,並不使用反斜槓字符?在Python中打印帶反斜槓的字符串2.7

>>> machines=['\\JIM-PC', '\\SUE-PC', '\\ANN-PC'] 
>>> for machine in machines: 
...  print 'Machine Found %s' % (machine) 
... 
Machine Found \JIM-PC 
Machine Found \SUE-PC 
Machine Found \ANN-PC 
+0

嘗試'print(repr(machine))' –

回答

1

最簡單的方法是將雙斜槓加倍,因爲「\\」被認爲是單斜槓字符。

machines=['\\\\JIM-PC','\\\\SUE-PC','\\\\ANN-PC'] 
for machine in machines: 
    print 'Machine Found %s' % (machine) 

您也可以使用該方法str.encode(「字符串轉義」):

machines=['\\JIM-PC','\\SUE-PC','\\ANN-PC'] 
for machine in machines: 
    print 'Machine Found %s' % (machine.encode('string-escape')) 

或者,你可以賦值爲好,如果你想編碼粘到變量供以後使用。

machines=['\\JIM-PC','\\SUE-PC','\\ANN-PC'] 
for machine in machines: 
    machine = machine.encode('string-escape') 
    print 'Machine Found %s' % (machine) 

我發現str.encode( '字符串轉義')方法在這裏:casting raw strings python

希望這有助於。

編輯

重新克里斯:打印(再版(機))的作品也一樣,只要你不介意它包括引號。

+0

感謝allan,''.encode('string-escape')就是我在尋找的 – Craig

0

字符串文字'\\JIM-PC'不包含雙反斜槓;你看到的是表示在一個常規的字符串文字中的單個反斜槓。

這很容易通過觀察所述字符串的長度,或遍歷其單個字符所示:

>>> machine = '\\JIM-PC' 
>>> len(machine) 
7 
>>> [c for c in machine] 
['\\', 'J', 'I', 'M', '-', 'P', 'C'] 

要創建包含一個雙反斜線的字符串,你可以使用一個raw string literalr'\\JIM-PC',或用正則字符串文字代表兩個反斜槓:'\\\\JIM-PC'

+0

相關:http://stackoverflow.com/questions/24085680/爲什麼-DO反斜槓-出現,兩次 –