Triple-quoted Strings
April 20th, 2009
In Python, if you use three double quotes (I know, that just looks weird when written) you don’t have to escape newlines. For instance, I’m working with a query (it’s much longer, I cut out the middle):
1 2 3 4 5 6 7 8 9 10 11 12 | _packageStatement_remove = """ select distinct pn.name name, pe.epoch epoch, pe.version version, pe.release release, pa.label arch from rhnActionPackage ap, rhnPackage p, [snip] and ap.package_arch_id = pa.id(+) and p.id = cp.package_id""" |
In Java, that’d be a lot uglier. I have no desire to convert the entire query, but it’d look something like:
1 2 3 4 5 6 7 8 | String query = "select distinct " + " pn.name name, " + " pe.epoch epoch, " + " pe.version version, " + " pe.release release, " + " pa.label arch " + [snip] |
Also keep in mind that in most cases, you have to be careful to add the space after each line within the quotes. Otherwise, when Java munges this all into a single constant, you’ll get two words merged into one:
1 2 | String foo = "golden" + "monkey"; |
The contents of foo is simply "goldenmonkey" without any spaces. Needless to say, that can really screw with your query.
Score one for Python.

