Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Too long raw string, multiple lines

Tags:

python

I am using python on windows and the path of my project folder is way too long. For example:

pathProject = r'C:\Users\Account\OneDrive\Documents\Projects\2016\Shared\Project-1\Administrative\Phase-1\Final'

os.chdir(pathProject)

How can I break this very long strong into multiple lines in the most elegant way? I know how to do it if the string is not a raw string. However, if I try something like this, I get an error:

pathProject = r'''C:\Users\Account\OneDrive\
                Documents\Projects\2016\Shared\
                Project-1\Administrative\Phase-1\
                Final'''

What is the most elegant way to break this raw string into multiple lines?

like image 558
Finn_py Avatar asked Feb 05 '17 23:02

Finn_py


People also ask

How do you break a long string into multiple lines 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 you safely break a long Python statement across multiple lines?

You cannot split a statement into multiple lines in Python by pressing Enter . Instead, use the backslash ( \ ) to indicate that a statement is continued on the next line.

How do you break a long statement into multiple lines?

To break a single statement into multiple linesUse the line-continuation character, which is an underscore ( _ ), at the point at which you want the line to break.

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

If you have a very long line of code in Python and you'd like to break it up over over multiple lines, if you're inside parentheses, square brackets, or curly braces you can put line breaks wherever you'd like because Python allows for implicit line continuation.


2 Answers

You can use parenthesis to trigger automatic line continuation. The strings will be automatically concatenated.

pathProject = (
    r"C:\Users\Account\OneDrive"
    r"\Documents\Projects\2016\Shared"
    r"\Project-1\Administrative\Phase-1\Final"
)
like image 131
Brendan Abel Avatar answered Oct 18 '22 11:10

Brendan Abel


You almost got it! The issue is that raw strings cannot end with a backslash. Hence, this works:

pathProject = r'''C:\Users\Account\OneDrive
\Documents\Projects\2016\Shared
\Project-1\Administrative\Phase-1
\Final'''

Note that if you put spaces into the triple-quoted string to indent it, like in your example, there will be spaces in your string, which you don't want. If you like indents, you can use automatic line continuation with parentheses as suggested in Brendan's answer. Again, make sure that the lines don't end with a backslash.

like image 5
Joooeey Avatar answered Oct 18 '22 12:10

Joooeey