簡體   English   中英

如何創建包含單引號和雙引號 python 的字符串?

[英]How can I create a string that contains both single and double quotes python?

我想創建一個包含單引號和雙引號的 python 字符串,但我不知道該怎么做。

使用反斜杠。 例如。

x = 'Hello "double quotes", \'single quotes\''

或者

x = "Hello \"double quotes\", 'single quotes'"

現在

print(x)
>>> Hello "double quotes", 'single quotes'

除了所選引號字符的反斜杠,例如

'This string\'s needs include \'single\' and "double quotes"'  # Escape single only
"This string's needs include 'single' and \"double quotes\""   # Escape double only

您也可以使用三引號,只要字符串不以所選的三引號分隔符結尾,並且不需要嵌入的三引號(如果確實如此,您總是可以轉義):

'''This string's needs include 'single' and "double quotes"'''   # No escapes needed
"""This string's needs include 'single' and "double quotes\""""  # One escape needed at end

有幾種方法可以做到這一點:

  • 您可以使用反斜杠轉義用於字符串分隔符的引號:
    • my_string = 'I have "double quotes" and \'single quotes\' here'
  • 您可以使用三引號:
    • my_string = """Put whatever "quotes" you 'want' here"""
  • 單獨執行並連接:
    • full_string = 'First "double-quotes", then ' + "'single quotes'"
  • 格式化字符串以插入所需的引號:
    • full_string = 'First "double-quotes", then {}single quotes{}'.format("'","'")
  • 使用變量和 f 字符串:
    • single_quote = "'"; full_string = f'First "double-quotes", then {single_quote}single quotes{single_quote}'

希望對您有所幫助,祝您編碼愉快!

暫無
暫無

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

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