I am trying to write a one-line long string in Python but I would like to follow the line length guidelines by showing it in multiple lines in the editor.
Problem Example:
long_string = "This is a very long string. Since it is a one-line string, I really want to keep it without any new line. However, I don't like how it looks in my code and it is annoying me"
I would like to achieve something similar to this (more readable and tidy):
long_string = "This is a very long string. Since it is a one-line string, I really want \
to keep it without any new line. However, I don't like how it looks in my \
code and it is annoying me"
However, the output adds spaces and/or newlines:
This is a very long string. Since it is a one-line string, I really want to keep it without any new line. However, I don't like how it looks in my code and it is annoying me
Although I know that there are ways to achieve it (as the following examples), in my opinion, these ways are not so easy to maintain:
long_string = "".join(["This is a very long string."],
["Since it is a one-line string, I really want"],
["to keep it without any new line. However, I don't like how"],
["it looks in my code and it is annoying me"])
or
long_string = ("This is a very long string."
"Since it is a one-line string, I really want"
"to keep it without any new line. However, I don't like how"
" ...")
Does anyone know an easier way to tackle this problem? Thanks.
CodePudding user response:
The way that requires neither repeated quotes, nor backslash line terminators (both of which impede editing the text because those characters have to be moved around) is to use a triple-quoted string and then strip newlines.
long_string = """
This is a very long string. Since it is a one-line string, I really want to
keep it without any new line. However, I don't like how it looks in my code
and it is annoying me
""".replace('\n', '')
This works as-is when in module scope and flush left. In an indented block it's also possible within stdlib:
from textwrap import dedent
def foo():
long_string = dedent("""
This is a very long string. Since it is a one-line string, I really want
to keep it without any new line. However, I don't like how it looks in
my code and it is annoying me
""").replace('\n', '')
print(long_string)
foo()