Last active
August 29, 2015 14:09
-
-
Save pudquick/0f8041d3f533409247cb to your computer and use it in GitHub Desktop.
Uncommon variations on multi-line strings in python
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # Variations on a theme. | |
| # This first example uses a poorly documented trick in python regarding strings: | |
| # | |
| # https://docs.python.org/2/tutorial/introduction.html | |
| # "Two or more string literals (i.e. the ones enclosed between quotes) next to each other | |
| # are automatically concatenated." | |
| # | |
| # Then it's combined with the python implied line continuation by wrapping it in an outer | |
| # set of parentheses. | |
| example1 = ( | |
| 'A line here\n' | |
| 'Another line there\n' | |
| 'The last line here.' | |
| ) | |
| print example1 | |
| # An alternate example using implicit line continuation, allowing removal of the parentheses | |
| example2 = 'A line here\n' \ | |
| 'Another line there\n' \ | |
| 'The last line here.' | |
| print example2 | |
| # Another variation is instead to add commas between strings enclosed in brackets or | |
| # parentheses to turn it into an iterable set of strings. Then use a string join with a single | |
| # newline character to create the multi-line string. | |
| # | |
| # This is the method I like the most. | |
| example3 = ( | |
| 'A line here.', | |
| 'Another line there.', | |
| 'The last line here.' | |
| ) | |
| print '\n'.join(example3) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment