如何创建同时包含单引号和双引号python的字符串?

时间:2020-06-03 14:22:34

标签: python

我想创建一个在字符串中同时包含单引号和双引号的python字符串,但是我不知道该怎么做。

3 个答案:

答案 0 :(得分:1)

使用反斜杠。例如。

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

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

现在

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

答案 1 :(得分:1)

除了所选引号字符的反斜杠外,例如

'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

答案 2 :(得分:0)

有几种方法可以做到这一点:

  • 您可以使用反斜杠转义用于字符串定界符的引号:
    • 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}'

希望有帮助,编码愉快!

相关问题