Writing a string (with new lines) in Python

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.


Have you tried to modify your string the following way:

stringtowrite = "abcd ||\nefgh||\niklk"

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

OR:

stringtowrite = """abcd ||
                   efgh||
                   iklk"""

Tags:

Python