python-3.x - 如何在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()
不成功。
解决方案
这对我有用:
with open('file.txt','w') as file:
print('\r\nthis is the second line\r\n\tthis line is indentedd\r\n',file=file)
推荐阅读
- python - 带有 Redis BackendResult 的 Celery AsyncResult 奇怪的行为
- amazon-web-services - 如何将发布(带有替换变量的包)上传到 S3 以便使用 codedeploy 进行部署
- angular - 导入 mat-checkbox 时出现角度材料错误
- php - 未定义变量:注册用户中的值
- r - 根据列名在 R 中附加数据框
- python - Python Regex:如何仅在双引号内转义字符
- javascript - HTML5
- indexing - Ravendb 索引中的空列表创建异常
- react-native - 如何创建反应原生布局
- python - 索引超出范围时如何跳过索引[Python]