Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Writing a string (with new lines) in Python

Tags:

python

I have to write strings with newlines and a specific structure to files in Python. When I do

 stringtowrite = "abcd ||
                   efgh||
                   iklk"

f = open(save_dir + "/" +count+"_report.txt", "w")
f.write(stringtowrite)
f.close()

I'm getting this error:

SyntaxError: EOL while scanning string literal

How can I write the string as it is to a file without deleting the new lines?

like image 337
Sapphire Avatar asked Aug 16 '11 18:08

Sapphire


People also ask

How do you insert a new line into a string of text?

In Windows, a new line is denoted using “\r\n”, sometimes called a Carriage Return and Line Feed, or CRLF. Adding a new line in Java is as simple as including “\n” , “\r”, or “\r\n” at the end of our string.

How do you write on different lines in Python?

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. In the revised version of the script, a blank space and an underscore indicate that the statement that was started on line 1 is continued on line 2.

What does '\ r mean in Python?

In Python strings, the backslash "\" is a special character, also called the "escape" character. It is used in representing certain whitespace characters: "\t" is a tab, "\n" is a newline, and "\r" is a carriage return.

How do you print a new line in Python?

Just use \n ; Python automatically translates that to the proper newline character for your platform.


1 Answers

The simplest thing is to use python's triple quotes (note the three single quotes)

stringtowrite = '''abcd ||
                   efgh||
                   iklk'''

any string literal with triple quotes will continue on a following line. You can use ''' or """.

By the way, if you have

a = abcd
b = efgh
c = iklk

I would recommend the following:

stringtowrite = "%s||\n%s||\n%s" % (a,b,c)

as a more readable and pythonic way of doing it.

like image 113
Peter V Avatar answered Oct 28 '22 00:10

Peter V