0

I'd like to save the following characters 'bar" as a string variable, but it seems to be more complicated than I thought :

  • foo = 'bar" is not a valid string.
  • foo = ''bar"' is not a valid string either.
  • foo = '''bar"'' is still not valid.
  • foo = ''''bar"''' actually saves '\'bar"'

What is the proper syntax in this case?

Dimitris Fasarakis Hilliard
  • 150,925
  • 31
  • 268
  • 253
Crolle
  • 822
  • 3
  • 10
  • 20

1 Answers1

2

The last string saves '\'bar"' as the representation, but it is the string you're looking for, just print it:

foo = ''''bar"'''
print(foo)
'bar"

when you hit enter in the interactive interpreter you'll get it's repr which escapes the second ' to create the string.

Using a triple quoted literal is the only way to define this without explicitly using escapes. You can get the same result by escaping quotes:

print('\'foo"')
'foo"
print("'foo\"")
'foo"
Dimitris Fasarakis Hilliard
  • 150,925
  • 31
  • 268
  • 253