簡體   English   中英

python中的雙引號和單引號

[英]double and single quotes in python

你好,我目前正在學習python,我一直被困在我的電子書中寫的這個小腳本中。

formatter = "%r %r %r %r"

print formatter %(1, 2, 3, 4)
print formatter %("one", "two", "three", "four")
print formatter %(True, False, False, True)
print formatter %(formatter, formatter, formatter, formatter)
print formatter %(
    "I had this thing.",
    "That you could type up right.",
    "But it didn't sing.",
    "So I said goodnight."
)

當我運行代碼時,其他所有字符串都用單引號引起來,但是“但是沒有唱歌”用雙引號引起來。 在嘗試了幾種語法后,我了解到單引號與此無關。 但是為什么會這樣呢? 如果我將該行分配給變量並像打印那樣

yathartha = "But it didn't happen"
print "%r" %yathartha 

輸出為帶有雙引號的“但是沒有發生”。 難道不應該有單引號嗎?

好吧,當您談論一個字符串時,它出現在引號之間,因此,如果您的字符串包含一個單引號,則不能使用單引號將其括起來,因為如果它以一個單引號開頭,它將結束用第一個單引號引起來。

yathartha = "But it didn't happen"
string_var = "%r" %yathartha 
print string_var

如果您的字符串用單引號引起來,那么將存儲在string_var中的字符串將為“ But it not”,因為那是遇到的結尾引號。

暫無
暫無

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

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