首页 > 解决方案 > 如何在python3中打印带有嵌入空格的字符串

问题描述

假设以下字符串:

s = '\r\nthis is the second line\r\n\tthis line is indented\r\n'

如果我以交互方式运行 Python (v. 3.8.6),打印此字符串将按预期工作:

>>> print(s)

this is the second line
        this line is indented

>>>

但是当我将此字符串打印到文件(即,print(s, file = "string.txt"))时,不会解释嵌入的空格,并且文本文件包含字面上的字符串(使用“\t”而不是制表符等)。

如何将相同的交互式输出写入文件?尝试使用str(), f-strings 和format()不成功。

标签: python-3.xstring-formatting

解决方案


这对我有用:

with open('file.txt','w') as file:
  print('\r\nthis is the second line\r\n\tthis line is indentedd\r\n',file=file)

推荐阅读