简体   繁体   中英

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

I want to create a python string that includes both single and double quotes in the string but I don't know how to do this.

Use backslashes. Eg.

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

or

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

Now

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

In addition to backslashes for the chosen quote character, eg

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

you can also use triple quotes, so long as the string doesn't end in the chosen triple quote delimiter, and doesn't need embedded triple quotes (which you can always escape if it does):

'''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

There are a few ways to do this:

  • You can escape the quote you use for your string delimiter with backslash:
    • my_string = 'I have "double quotes" and \'single quotes\' here'
  • You can use triple-quotes:
    • my_string = """Put whatever "quotes" you 'want' here"""
  • Do it separately and concatenate:
    • full_string = 'First "double-quotes", then ' + "'single quotes'"
  • Format the string to insert the needed quotes:
    • full_string = 'First "double-quotes", then {}single quotes{}'.format("'","'")
  • Use variables and f-strings:
    • single_quote = "'"; full_string = f'First "double-quotes", then {single_quote}single quotes{single_quote}'

Hope that helps, happy coding!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM