在Python中,表示换行主要有以下几种方法:
1. 使用反斜杠 `\`:
print("第一行\n第二行\n第三行")
2. 使用三引号字符串:
result = """第一行
第二行
第三行"""
print(result)
3. 使用 `print` 函数:
print("第一行\n第二行\n第三行")
4. 使用 `f-string`(Python 3.6及以上版本):
line1 = "第一行"
line2 = "第二行"
line3 = "第三行"
result = f"{line1}\n{line2}\n{line3}"
print(result)
5. 使用括号隐式换行:
fruits = ['apple', 'banana', 'cherry', 'date']
print(fruits)
6. 使用 `os.linesep` 确保跨平台兼容性:
import os
filename = "D:\\test.txt"
with open(filename, 'w') as fp:
while True:
strinput = input("输入字符串(输入.退出): ")
if strinput:
fp.write("%s%s" % (strinput, os.linesep))
else:
break