繁体   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