Decaff Decaff - 1 month ago 4
Python Question

Python 3 print to file with mix of " and ' in string

I am creating an HTML output file using vanilla Python 3 and I wish to use the multi-tab layout (http://www.w3schools.com/howto/tryit.asp?filename=tryhow_js_tabs_close) to help organize my presentation.

When trying to print:

' <li><a href="#" class="tablinks active" onclick="openTab(event, 'Faults')"><b>Faults</b></a></li>'
I run into a situation where I need to include (') and (") characters in the string. I have tried to only use (") characters inside the string and use (') to define the string, however this breaks the html functionality of the code.

If I use
'partial string {}Faults{} more string'.format("'","'")
I see this output:

' <li><a href="#" class="tablinks active" onclick="openTab(event, \'Faults\')"><b>Faults</b></a></li>)'


Similarly if I attempt to join strings together,

b = ' <li><a href="#" class="tablinks active" onclick="openTab(event, '
c = "'Faults'"
d = ')"><b>Faults</b></a></li>)
('').join([b,c,d])


I get the exact same thing as my first attempt.

' <li><a href="#" class="tablinks active" onclick="openTab(event, \'Faults\')"><b>Faults</b></a></li>)'


Is there any way to get around this issue while printing to a file?
Thank you.

Answer

' <li><a href="#" class="tablinks active" onclick="openTab(event, \'Faults\')"><b>Faults</b></a></li>'

You need to escape single quotes in single quotes. If you write this to a file, it will be how you want it.

Or use ''' <li><a href="#" class="tablinks active" onclick="openTab(event, \'Faults\')"><b>Faults</b></a></li>'''

Notice the triple quotes?

Interesting article about escaping in Python: Learn Python the hard way