Python: a nest of more than two types of quotes

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

 subprocess.Popen('echo "var1+'hello!'+var2"', shell=True) 
+4
source share
3 answers

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

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

If you want to use the same triple quotes as the separator and inside the string, you need to avoid the quotes in the string:

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

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

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

Note that this way you can even mix raw strings with jagged strings:

 In [17]: print('non\traw' r'\traw' 'non\traw') non raw\trawnon raw 
+6
source

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

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

You can use triple quotes:

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

Source: https://habr.com/ru/post/1500554/


All Articles