簡體   English   中英

需要立即在Python 2.6中使用雙引號和單引號引起來的字符串

[英]Need a string with double quote immediately followed by single quote in python 2.6

我正在嘗試在變量A存儲一個字符串,其中包含:

"'D:\\Work\\B1.tif';'D:\\Work\\B2.tif'"

我有兩個變量存儲B1.tifB2.tif的位置:

X = "D:\\Work\\B1.tif"
Y = "D:\\Work\\B2.tif"

但是,當我嘗試將所有字符串組合成變量“ A”時:

A = '"' + "'" + X + "'" + ";" + "'" + Y + "'" + '"'

它存儲為:

'"\'D:\\Work\\B1.tif\';\'D:\\Work\\B2.tif\'"'

當我print A時顯示:

"'D:\Work\B1.tif';'D:\Work\B2.tif'"

似乎將雙引號( " )和單引號( " )分開的反斜杠( \\ )自動存儲在字符串中。 如何在字符串中存儲雙引號和單引號而不用反斜杠分隔引號?

字符串格式化(和原始字符串)要容易得多:

A = "\"'D:\\Work\\B1.tif';'D:\\Work\\B1.tif'\""
print A

X = r"D:\Work\B1.tif" 
Y = r"D:\Work\B2.tif"

A = '"' + "'" + X + "'" + ";" + "'" + Y + "'" + '"'
print A

A = "\"'%s';'%s'\"" % (X, Y)
print A

給出:

"'D:\Work\B1.tif';'D:\Work\B1.tif'"
"'D:\Work\B1.tif';'D:\Work\B2.tif'"
"'D:\Work\B1.tif';'D:\Work\B2.tif'"

但是,要獲得顯示的結果,必須使用repr() ,如果僅在其中鍵入變量名稱,則IDLE會使用它。如果我將所有print語句更改為print repr(A)則會得到:

'"\'D:\\Work\\B1.tif\';\'D:\\Work\\B1.tif\'"'
'"\'D:\\Work\\B1.tif\';\'D:\\Work\\B2.tif\'"'
'"\'D:\\Work\\B1.tif\';\'D:\\Work\\B2.tif\'"'

IDLE使用類的__repr__()方法, print使用__str__() 通常,它們是相同的,但有時與此處不同。

打印'“ \\'%s \\'; \\'%s \\'”'%(X,Y)

當您僅通過鍵入變量的名稱在Python中顯示變量時,Python會嘗試以某種方式打印該變量,如果您將其復制並粘貼為變量,則會產生相同的對象。 這適用於字符串,列表,字典,集合等。結果是,以這種方式打印時需要轉義字符串。 齒隙實際上沒有存儲在字符串中。 您可以通過計算長度來看到:

>>> a = '"' + "'"
>>> a
'"\''
>>> len(a)
2
>>> print a
"'

但是,有更好的方法來構建所需的相同字符串,如其他答案所示。

對於這些復雜的格式化情況,請嘗試使用str.format() ,甚至可以使用三引號引起來的字符串來str.format()此操作。

A = ''' "'{}';'{}'" '''.format(X,Y)

暫無
暫無

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

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