Skip to content
Fix Code Error

Pythonic way to create a long multi-line string

March 13, 2021 by Code Error
Posted By: Anonymous

I have a very long query. I would like to split it in several lines in Python. A way to do it in JavaScript would be using several sentences and joining them with a + operator (I know, maybe it’s not the most efficient way to do it, but I’m not really concerned about performance in this stage, just code readability). Example:

var long_string = 'some text not important. just garbage to' +
                  'illustrate my example';

I tried doing something similar in Python, but it didn’t work, so I used to split the long string. However, I’m not sure if this is the only/best/pythonicest way of doing it. It looks awkward.
Actual code:

query = 'SELECT action.descr as "action", '
    'role.id as role_id,'
    'role.descr as role'
    'FROM '
    'public.role_action_def,'
    'public.role,'
    'public.record_def, '
    'public.action'
    'WHERE role.id = role_action_def.role_id AND'
    'record_def.id = role_action_def.def_id AND'
    'action.id = role_action_def.action_id AND'
    'role_action_def.account_id = ' + account_id + ' AND'
    'record_def.account_id=' + account_id + ' AND'
    'def_id=' + def_id

Solution

Are you talking about multi-line strings? Easy, use triple quotes to start and end them.

s = """ this is a very
        long string if I had the
        energy to type more and more ..."""

You can use single quotes too (3 of them of course at start and end) and treat the resulting string s just like any other string.

NOTE: Just as with any string, anything between the starting and ending quotes becomes part of the string, so this example has a leading blank (as pointed out by @root45). This string will also contain both blanks and newlines.

I.e.,:

' this is a veryn        long string if I had then        energy to type more and more ...'

Finally, one can also construct long lines in Python like this:

 s = ("this is a very"
      "long string too"
      "for sure ..."
     )

which will not include any extra blanks or newlines (this is a deliberate example showing what the effect of skipping blanks will result in):

'this is a verylong string toofor sure ...'

No commas required, simply place the strings to be joined together into a pair of parenthesis and be sure to account for any needed blanks and newlines.

Answered By: Anonymous

Related Articles

  • What does this symbol mean in JavaScript?
  • How to prevent scrolling the whole page?
  • Navbar not filling width of page when reduced to mobile view
  • Introducing FOREIGN KEY constraint may cause cycles…
  • How to use JSON to power interactive Backbone.js app
  • What is your most productive shortcut with Vim?
  • Polymer - styling childnodes of host
  • How to change the for loop in my code to give me an…
  • SQL query return data from multiple tables
  • Proper use of the IDisposable interface
  • Why doesn't C++ have a garbage collector?
  • Stack, Static, and Heap in C++
  • What are the undocumented features and limitations…
  • Can't install via pip because of egg_info error
  • Jquery fadeToggle Trouble
  • get unique record counts of two joined tables
  • How do I merge two dictionaries in a single…
  • no match for ‘operator
  • How to change the for loop in the code to give me an…
  • lexers vs parsers
  • data.table vs dplyr: can one do something well the…
  • Running stages in parallel with Jenkins workflow / pipeline
  • Sample task application with drag and drop
  • Database development mistakes made by application developers
  • Binding complex object to a component
  • Reference — What does this symbol mean in PHP?
  • Is it possible to apply CSS to half of a character?
  • What's the difference between eval, exec, and compile?
  • What is the copy-and-swap idiom?
  • Logging best practices
  • insert tables in dataframe with years from 2000 to…
  • Reference - What does this regex mean?
  • Passing Parameters JavaFX FXML
  • polymer 1.0 event firing among nested components
  • Memcached vs. Redis?
  • regEx rule negative
  • How to execute next stage in sequential stages…
  • How can I pass a wct test while rearranging children…
  • how to get text from textview
  • How to use html template with vue.js
  • How to implement an STL-style iterator and avoid…
  • Pandas pivot_table: filter on aggregate function
  • Usage of __slots__?
  • How to turn off ALL conventions in Entity Framework Core 5
  • How do SO_REUSEADDR and SO_REUSEPORT differ?
  • Backbone.js - Should nested Views maintain…
  • PHP parse/syntax errors; and how to solve them
  • Why does C++ code for testing the Collatz conjecture…
  • The definitive guide to form-based website authentication
  • SQL find sum of entries by date including previous date
  • TypeScript: Turn a Container into Maybe
  • Smart way to truncate long strings
  • ORA-01008: not all variables bound. They are bound
  • What is the garbage collector in Java?
  • What is JavaScript garbage collection?
  • Overloading operators in typedef structs (c++)
  • JavaFX - create custom button with image
  • Best way to replace multiple characters in a string?
  • What is an optional value in Swift?
  • What is a "cache-friendly" code?
  • Why is reading lines from stdin much slower in C++…
  • How do I obtain a Query Execution Plan in SQL Server?
  • Virtual Memory Usage from Java under Linux, too much…
  • Fix top buttons on scroll of list below
  • How I can parser table values from google apps script
  • Why is Google Firebase not recommended by Google -…
  • Easiest way to ignore blank lines when reading a…
  • For-each over an array in JavaScript
  • How can I manually compile a svelte component down…
  • custom text position on ipywidgets button
  • Auto-fit TextView for Android
  • How to filter a RecyclerView with a SearchView
  • Does reading an entire file leave the file handle open?
  • NullpointerException error while working with…
  • What is The Rule of Three?
  • How to solve java.lang.OutOfMemoryError trouble in Android
  • Jenkins build step fails when running npm install command
  • How can I find the product GUID of an installed MSI setup?
  • What is a NullReferenceException, and how do I fix it?
  • Getting started with Haskell
  • Calculator: Back key doesnt work in Javascript
  • How to split a file into equal parts, without…
  • close fxml window by code, javafx
  • Exponentiation in Python - should I prefer **…
  • Fast way of finding lines in one file that are not…
  • Why does the arrow (->) operator in C exist?
  • Confused with basic java stuffs
  • What does "Fatal error: Unexpectedly found nil while…
  • Jenkins pipeline if else not working
  • Using Auto Layout in UITableView for dynamic cell…
  • How to "properly" create a custom object in JavaScript?
  • Label not displaying text even after change (JavaFX)
  • Best practice multi language website
  • apache server reached MaxClients setting, consider…
  • Plotting sentences in Wordcloud in R
  • C++ template,typename and operator
  • Improve INSERT-per-second performance of SQLite
  • Vue.js $set not updating the display
  • Aurelia UX showcase app fails to load
  • Java Garbage Collection Log messages

Disclaimer: This content is shared under creative common license cc-by-sa 3.0. It is generated from StackExchange Website Network.

Post navigation

Previous Post:

Resolving javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed Error?

Next Post:

Avoiding NullPointerException in Java

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

.net ajax android angular arrays aurelia backbone.js bash c++ css dataframe ember-data ember.js excel git html ios java javascript jquery json laravel linux list mysql next.js node.js pandas php polymer polymer-1.0 python python-3.x r reactjs regex sql sql-server string svelte typescript vue-component vue.js vuejs2 vuetify.js

  • you shouldn’t need to use z-index
  • No column in target database, but getting “The schema update is terminating because data loss might occur”
  • Angular – expected call-signature: ‘changePassword’ to have a typedeftslint(typedef)
  • trying to implement NativeAdFactory imports deprecated method by default in flutter java project
  • What should I use to get an attribute out of my foreign table in Laravel?
© 2022 Fix Code Error