簡體   English   中英

Python字符串文字-字符串中包括單引號和雙引號

[英]Python string literals - including single quote as well as double quotes in string

我想加入這一系列的字符串:

my_str='"hello!"' + " it's" + ' there'

希望結果是:

my_str
Out[65]: '"hello!" it's there'

但是我得到:

my_str
Out[65]: '"hello!" it\'s there'

我嘗試了幾次迭代,但似乎都沒有效果。

結果是正確的。 單引號必須在單引號字符串中轉義。 雙引號相同。

如果您嘗試print結果,您會發現它與預期的一樣。

>>> print(my_str)
"hello!" it's there

如果使用print命令,您將看到所需的...

>>> my_str='"hello!"' + " it's" + ' there'
>>> my_str
'"hello!" it\'s there' #Count printed characters. You will count 22
>>> print my_str
"hello!" it's there
#Now count characters. 19
>>> len(my_str)
19
#see count of characters.

僅使用“ my_str”而不使用任何命令/功能僅顯示內存。 但是,如果要使用字符串u進行處理,則將得到“'”而不包含“ \\” ...

print my_str將您的字符串打印為

'"hello!" it's there'

您還可以使用my_str.decode('ascii')以另一種方式執行該操作

new_str = my_str.decode('ascii')
print new_str

它將字符串打印為:

"hello!" it's there

暫無
暫無

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

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