Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Breaking long string without the spaces in Python

Tags:

python

string

So, here is a snippet of my code:

return "a Parallelogram with side lengths {} and {}, and interior angle 
{}".format(str(self.base), str(self.side), str(self.theta)) 

It goes beyond the 80 chars for good styling in a line, so I did this:

return "a Parallelogram with side lengths {} and {}, and interior angle\
{}".format(str(self.base), str(self.side), str(self.theta)) 

I added the "\" to break up the string, but then there is this huge blank gap when I print it.

How would you split the code without distorting it?

Thanks!

like image 948
muros Avatar asked Oct 04 '13 23:10

muros


People also ask

How do you split a string in Python without spaces?

Use the list() class to split a string into a list of strings. Use a list comprehension to split a string into a list of integers.

How do you split a long string in Python?

You can have a string split across multiple lines by enclosing it in triple quotes. Alternatively, brackets can also be used to spread a string into different lines. Moreover, backslash works as a line continuation character in Python. You can use it to join text on separate lines and create a multiline string.

How do I fix the line is too long in Python?

The preferred way of wrapping long lines is by using Python's implied line continuation inside parentheses, brackets and braces. If necessary, you can add an extra pair of parentheses around an expression, but sometimes using a backslash looks better. Make sure to indent the continued line appropriately.


1 Answers

You can put parenthesis around the whole expression:

return ("a Parallelogram with side lengths {} and {}, and interior "
        "angle {}".format(self.base, self.side, self.theta))

or you could still use \ to continue the expression, just use separate string literals:

return "a Parallelogram with side lengths {} and {}, and interior " \
       "angle {}".format(self.base, self.side, self.theta)

Note that there is no need to put + between the strings; Python automatically joins consecutive string literals into one:

>>> "one string " "and another"
'one string and another'

I prefer parenthesis myself.

The str() calls are redundant; .format() does that for you by default.

like image 160
Martijn Pieters Avatar answered Sep 23 '22 06:09

Martijn Pieters