r/pythontips • u/rochacbruno • Jun 03 '16
Syntax Use parenthesis to wrap long strings
Sometimes we have that long text to write in a single line
LONG_TEXT = "this is a very long text written in just one line of code"But sometimes it is better to use parenthesis syntax to have a better readability and to fit the 80 chars limit.
LONG_TEXT = (
'this is ' # no commas here!
'a very '
'long text '
'written in '
'multiple lines of code'
)Sometimes it is useful.
The caveat is that if someone thinks it is a tuple and adds , in the end of each line, LONG_TEXT will be a sequence of strings.
LONG_TEXT = (
'this is ',
...
)4
u/krato1995 Jun 04 '16 edited Jun 04 '16
Some comments proposed multiline strings with triple quotes and with a backslash at the end of the line. Personally I use either of the two depending on how long the string will be. I never used the parentheses approach.
Which is actually the best? PEP compliant perhaps?
3
u/tcas71 Jun 04 '16
Triples quotes are different from the other uses since it takes the line breaks into account. If you just want to split a long single-lined string into multiple lines in your code (for readability and/or PEP8), it doesn't works quite well (unless you remove the \n, but that's some pointless complexity IMHO).
I don't know PEP8 by hearth, but my editor's linter is OK with both parenthesis and backslashes. What's not OK is using both at the same time (and generally speaking any unnecessary use of backslashes).
5
u/DrMaxwellEdison Jun 03 '16
A similar method is to use multiline strings using triple-quotes. They look cleaner and are easier to write, but note that they are not strictly identical.
Example:
LONG_TEXT = """this is
a very
long text
written in
multiple lines of code"""The caveat to this is that multiline strings append \n and extra spacing as need to made almost precisely what is written.
A workaround for the spacing can be to drop the indent level on the text (python does not through syntax errors for indent levels for this case):
LONG_TEXT = """this is
a very
long text
written in
multiple lines of code"""As for the \n character, you can remove all instances using .replace():
LONG_TEXT = LONG_TEXT.replace('\n', ' ')Like I said, multilines are not equivalent to OP's tip, and it takes some extra work to make them equivalent. However, sometimes you really want a multiline string with line breaks and extra spacing, or you don't mind taking the extra processing steps if it means you can write strings more easily. So there you go. :)
Final note: some folks mistake multiline strings for multiline comments*. While they can function in the same way, the strings are actual objects in memory and can be assigned to a variable to use later, if you wish. Python allows you to write literal objects without assigning them to anything: the object is created, stored briefly, and a second later is not referenced, so garbage collection removes it.
On the other hand, these multiline strings are typically used as docstrings, which allow you to create documentation automatically using tools like docutils. Check the first link for more details.
*Python does not have explicit multiline comment support. Instead, you must use multiple lines of comments using
#
3
u/theOdysseyEffect Jun 04 '16
When did Python stop allowing multiline comments?
1
u/DrMaxwellEdison Jun 04 '16
Python never really had an explicit multiline comment, but you can use multiline strings in normal code. The string will be created in memory when the line is executed, but then it is immediately discarded.
Functionally, that usage works as a comment, but it's not technically a comment. Hope that makes sense.
1
u/das_ist_nuemberwang Jun 04 '16
The string will be created in memory when the line is executed, but then it is immediately discarded.
Not true. From the link I posted above:
Python tip: You can use multi-line strings as multi-line comments. Unless used as docstrings, they generate no code! :-)
2
u/DrMaxwellEdison Jun 04 '16
I did some more searching around to verify this and you are correct, not just from Guido's tweet. Others have verified that a multiline string used as a comment that isn't a docstring will generate no bytecode. So, that works.
Good catch, thank you. :)
Note that PEP 8 does recommend using standard
#comments, one per line, to form a block comment, but of course, PEP 8 is just a guideline.2
u/das_ist_nuemberwang Jun 04 '16
Instead of hugging the left margin, textwrap.dedent will make your source code look much nicer.
2
2
u/groovitude Jun 04 '16
>>> print (
'You can '
'even use {0} '
'with it.'
).format('format()')
You can even use format() with it.
>>> print (
'Alternately, you can '
'put the {0} inside '
'the parenthesis.'.format('format()')
)
Alternately, you can put the format() inside the parenthesis.1
u/Contrum Jun 04 '16
>>> print("You don't need to use {} if the {} is consistent.".format("numbers", order")) You don't need to use numbers if the order is consistent.
1
u/tcas71 Jun 04 '16
if someone thinks it is a tuple and adds , in the end of each line
Even less than that, a single comma anywhere breaks the behavior, even at the end:
# This is a string
("This is a "
"long string")
# This is a singleton tuple
("This is NOT a "
"long string", )
9
u/vriljam 3.4.3 Jun 03 '16
I guess you can use backslashes too: