开发者

Writing a string (with new lines) in 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?


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"""


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.


You can add the \ character to the end of each line, which indicates that the line is continued on the next line, you can triple-quote the string instead of single-quoting it, or you can replace the literal newlines in the string with \n.


You can write newlines – \n – into your string.

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


Try this:

stringtowrite = f"abcd ||\nefgh||\niklk"
f = open(save_dir + "/" +count+"_report.txt", "w")
f.write(stringtowrite)
f.close()
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜