James Lee
James Lee

Reputation: 21

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.

Upvotes: 0

Views: 2355

Answers (3)

Sam
Sam

Reputation: 1415

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!

Upvotes: 3

ShadowRanger
ShadowRanger

Reputation: 155323

In addition to backslashes for the chosen quote character, e.g.

'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

Upvotes: 1

Eeshaan
Eeshaan

Reputation: 1635

Use backslashes. Eg.

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

or

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

Now

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

Upvotes: 1

Related Questions