簡體   English   中英

如何在值中顯示帶有單反斜杠的python樣式的字典?

[英]How to display a python-style dictionary with single backslashes in the value?

我遇到一個簡單但奇怪的問題。 我想使用以下句子來顯示類似{'file_path':'\\ 11.1.2.3 \\ file1'}的字典:

>>> mydict = {'file_path': '\\\\11.1.2.3\\file1'}
>>> mydict
{'file_path': '\\\\11.1.2.3\\file1'}

我在值字符串前面加上r

>>> mydict = {'file_path': r'\\11.1.2.3\file1'}
>>> mydict
{'file_path': '\\\\11.1.2.3\\file1'}

結果與前述結果相同,這是無法預期的。

任何人都可以提供一種顯示字典的方法,而不是僅打印值嗎? 提前致謝!

制作自己的打印功能:

mydict = {'file_path1': r'\\11.1.2.3\file1', 'file_path2': r'\\111232.3\blabla'}
pairs = []
for k,v in mydict.items():
    pairs.append("'%s': '%s'" % (k,v))
print '{' + ', '.join(pairs) + '}'

或者,如果您只想要一個特定的鑰匙。

mydict = {'file_path1': r'\\11.1.2.3\file1', 'file_path2': r'\\111232.3\blabla'}
pairs = []
for k,v in mydict.items():
    if k == 'file_path1':
        pairs.append("'%s': '%s'" % (k,v))
print '{' + ', '.join(pairs) + '}'

使用理解:

如果您真的要轉換轉義的字符。

>>> import codecs
>>> mydict = {'file_path': '\\\\11.1.2.3\\file1'}
>>> print(codecs.getdecoder("unicode_escape")(str(mydict))[0])
{'file_path': '\\11.1.2.3\file1'}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM