13

Is it possible to nest more than two types of quotation signs? I mean I know ' and " but what if i need more? Is this allowed:

subprocess.Popen('echo "var1+'hello!'+var2"', shell=True)
aldorado
  • 4,394
  • 10
  • 35
  • 46

3 Answers3

20

You can use triple-quotes to avoid any kind of problem with nested single quotes:

subprocess.Popen('''echo "var1+'hello!'+var2"''', shell=True)

In case you want to use the same triple-quotes as both a delimiter and inside the string then you have to escape the quotes in the string:

'''some\'\'\'triple quotes\'\'\'''' -> "some'''triple quotes'''"

Alternatively you can rely on the fact that the interpreter will concatenate consecutive string literals, and use different quotes for different parts of the string:

subprocess.Popen('echo "var1+' "'hello!'" '+var2"', shell=True)

Note that in this way you can even mix raw strings with non-raw strings:

In [17]: print('non\traw' r'\traw' 'non\traw')
non     raw\trawnon     raw
Bakuriu
  • 98,325
  • 22
  • 197
  • 231
6

Triple quotes work. You can use either ''' or """

subprocess.Popen('''echo "var1+'hello!'+var2"''', shell=True)
Paco
  • 4,520
  • 3
  • 29
  • 53
1

You can use triple quotes:

subprocess.Popen('''echo "var1+'hello!'+var2"''', shell=True)


subprocess.Popen("""echo "var1+'hello!'+var2\"""", shell=True)
Kara
  • 6,115
  • 16
  • 50
  • 57