我如何在Python中指定一个新行?

时间:2012-07-16 02:14:11

标签: python

如何在Python中指定新行?

要在String中与Java进行比较,您可以执行类似“First Line \ r \ nSecond Line”的操作。

那你将如何在Python中做到这一点?用于保存具有多行的文件。

14 个答案:

答案 0 :(得分:280)

这取决于你想要的正确程度。 \n通常会完成这项工作。如果你真的想要做对,你可以在os package中查找换行符。 (它实际上称为linesep。)

注意:使用Python API写入文件时,请勿使用os.linesep。只需使用\n; Python会自动将其转换为适合您平台的换行符。

答案 1 :(得分:40)

新行字符为\n。它在字符串中使用。

示例:

    print 'First line \n Second line' 

其中\n是换行符。

这会产生结果:

First line
 Second line

答案 2 :(得分:15)

您可以单独或在单个字符串内写入新行,这更容易。

示例1

输入

line1 = "hello how are you"
line2 = "I am testing the new line escape sequence"
line3 = "this seems to work"

您可以撰写' \ n'单独:

file.write(line1)
file.write("\n")
file.write(line2)
file.write("\n")
file.write(line3)
file.write("\n")

输出

hello how are you
I am testing the new line escape sequence
this seems to work

示例2

输入

正如其他人在之前的回答中指出的那样,将\ n放在字符串中的相关位置:

line = "hello how are you\nI am testing the new line escape sequence\nthis seems to work"

file.write(line)

输出

hello how are you
I am testing the new line escape sequence
this seems to work

答案 3 :(得分:9)

在Python中,您可以使用换行符,即\n

答案 4 :(得分:9)

如果您一次输入几行文字,我发现这是最易阅读的格式。

file.write("\
Life's but a walking shadow, a poor player\n\
That struts and frets his hour upon the stage\n\
And then is heard no more: it is a tale\n\
Told by an idiot, full of sound and fury,\n\
Signifying nothing.\n\
")

每行末尾的\转义新行(这会导致错误)。

答案 5 :(得分:5)

最简单的解决方案

如果你只是在没有任何参数的情况下调用print,它将输出一个空行。

print

您可以将输出传递给这样的文件(考虑您的示例):

f = open('out.txt', 'w')
print 'First line' >> f
print >> f
print 'Second line' >> f
f.close()

它不仅与操作系统无关(甚至不需要使用os包),它也比将\n放在字符串中更具可读性。

解释

print()函数有一个可选的关键字参数,用于字符串的结尾,称为end,默认为操作系统的换行符,例如。 \n。因此,当您调用print('hello')时,Python实际上正在打印'hello' + '\n'。这意味着当你只是在没有任何参数的情况下调用print时,它实际上是打印'' + '\n',这会产生换行符。

替代

使用多行字符串。

s = """First line
    Second line
    Third line"""
f = open('out.txt', 'w')
print s >> f
f.close()

答案 6 :(得分:4)

'\n'相同,但您可能不需要'\r'。您的Java版本中是否有这样的原因?如果你确实需要/想要它,你也可以在Python中以相同的方式使用它。

答案 7 :(得分:4)

\ n - 简单换行字符插入有效:

# Here's the test example - string with newline char :
In [36]: test_line = "Hi!!!\n testing first line.. \n testing second line.. \n and third line....."

# Output:
In [37]: print(test_line)

Hi!!!
 testing first line.. 
 testing second line.. 
 and third line.....

答案 8 :(得分:2)

Java中字符串文字中的大多数转义字符在Python中也有效,例如“\ r”,“\ n”

答案 9 :(得分:2)

平台独立换行器:linux,windows和其他

import os
name = 'bandham'+ os.linesep + 'manikanta'
print(name)

输出:

bandham
manikanta

答案 10 :(得分:2)

值得一提的是,当您使用交互式python shell或Jupyter笔记本检查字符串时,\n和其他反斜杠字符串(例如\t)会以字面意义呈现: >

>>> gotcha = 'Here is some random message...'
>>> gotcha += '\nAdditional content:\n\t{}'.format('Yet even more great stuff!')
>>> gotcha
'Here is some random message...\nAdditional content:\n\tYet even more great stuff!'

换行符,制表符和其他特殊的非打印字符仅在打印时或写入文件时才会呈现为空白

>>> print('{}'.format(gotcha))
Here is some random message...
Additional content:
    Yet even more great stuff!

答案 11 :(得分:0)

\ n分隔字符串的行。在下面的示例中,我将循环写记录。每条记录都用\n分隔。

f = open("jsonFile.txt", "w")

for row_index in range(2, sheet.nrows):

  mydict1 = {
    "PowerMeterId" : row_index + 1,
    "Service": "Electricity",
    "Building": "JTC FoodHub",
    "Floor": str(Floor),
    "Location": Location,
    "ReportType": "Electricity",
    "System": System,
    "SubSystem": "",
    "Incomer": "",
    "Category": "",
    "DisplayName": DisplayName,
    "Description": Description,
    "Tag": tag,
    "IsActive": 1,
    "DataProviderType": int(0),
    "DataTable": ""
  }
  mydict1.pop("_id", None)
  f.write(str(mydict1) + '\n')

f.close()

答案 12 :(得分:0)

如其他答案中所述:“换行符为\ n。它在字符串中使用”。

我发现最简单易读的方法是使用“格式”功能,使用nl作为新行的名称,然后将要打印的字符串分解为要打印的确切格式:

print("line1{nl}"
      "line2{nl}"
      "line3".format(nl="\n"))

这将输出:

line1
line2
line3

通过这种方式执行任务,还可以提高代码的可读性:)

答案 13 :(得分:0)

在 Python 3 中,该语言负责在平台的本机表示中为您编码换行符。这意味着在 Windows 上为 \r\n,在成熟的系统上为 \n

即使在 U*x 系统上,在文本模式下读取带有 Windows 行结尾的文件也会返回正确的文本结果,即 \r 字符之前的任何 \n 字符都会被静默删除。

如果您需要完全控制文件中的字节,您可以使用二进制模式。那么每个字节正好对应一个字节,Python 不执行任何转换。

>>> # Write a file with different line endings, using binary mode for full control
>>> with open('/tmp/demo.txt', 'wb') as wf:
...     wf.write(b'DOS line\r\n')
...     wf.write(b'U*x line\n')
...     wf.write(b'no line')
10
9
7

>>> # Read the file as text
>>> with open('/tmp/demo.txt', 'r') as text:
...     for line in text:
...         print(line, end='')
DOS line
U*x line
no line

>>> # Or more demonstrably
>>> with open('/tmp/demo.txt', 'r') as text:
...     for line in text:
...         print(repr(line))
'DOS line\n'
'U*x line\n'
'no line'

>>> # Back to bytes!
>>> with open('/tmp/demo.txt', 'rb') as binary:
...     for line in binary:
...         print(line)
b'DOS line\r\n'
b'U*x line\n'
b'no line'

>>> # Open in binary, but convert back to text
>>> with open('/tmp/demo.txt', 'rb') as binary:
...     for line in binary:
...         print(line.decode('utf-8'), end='')
DOS line
U*x line
no line

>>> # Or again in more detail, with repr()
>>> with open('/tmp/demo.txt', 'rb') as binary:
...     for line in binary:
...         print(repr(line.decode('utf-8')))
'DOS line\r\n'
'U*x line\n'
'no line'