标签归档:line-breaks

如何在python函数中打印换行符?

问题:如何在python函数中打印换行符?

我的代码中有一个字符串列表。

A = ['a1', 'a2', 'a3' ...]
B = ['b1', 'b2', 'b3' ...]

我想用换行符将它们打印出来,如下所示:

>a1
b1
>a2
b2
>a3
b3

我试过了:

print '>' + A + '/n' + B

但是/ n不像换行符那样被识别。

I have a list of strings in my code;

A = ['a1', 'a2', 'a3' ...]
B = ['b1', 'b2', 'b3' ...]

and I want to print them separated by a linebreak, like this:

>a1
b1
>a2
b2
>a3
b3

I’ve tried:

print '>' + A + '/n' + B

But /n isn’t recognized like a line break.


回答 0

你的斜线倒退了,应该是 "\n"

You have your slash backwards, it should be "\n"


回答 1

换行符实际上是'\n'

The newline character is actually '\n'.


回答 2

>>> A = ['a1', 'a2', 'a3']
>>> B = ['b1', 'b2', 'b3']

>>> for x in A:
        for i in B:
            print ">" + x + "\n" + i

输出:

>a1
b1
>a1
b2
>a1
b3
>a2
b1
>a2
b2
>a2
b3
>a3
b1
>a3
b2
>a3
b3

请注意,您使用的/n正确的!

>>> A = ['a1', 'a2', 'a3']
>>> B = ['b1', 'b2', 'b3']

>>> for x in A:
        for i in B:
            print ">" + x + "\n" + i

Outputs:

>a1
b1
>a1
b2
>a1
b3
>a2
b1
>a2
b2
>a2
b3
>a3
b1
>a3
b2
>a3
b3

Notice that you are using /n which is not correct!


回答 3

for pair in zip(A, B):
    print ">"+'\n'.join(pair)
for pair in zip(A, B):
    print ">"+'\n'.join(pair)

回答 4

换行符可以使用的所有三种方式:

'\n'

"\n"

"""\n"""

All three way you can use for newline character :

'\n'

"\n"

"""\n"""

回答 5

\n是一个转义序列,由反斜杠表示。正常的正斜杠,例如/n不会起作用。在您的代码中,您使用/n而不是\n

\n is an escape sequence, denoted by the backslash. A normal forward slash, such as /n will not do the job. In your code you are using /n instead of \n.


回答 6

您可以使用标准os库打印本机换行符

import os
with open('test.txt','w') as f:
    f.write(os.linesep)

You can print a native linebreak using the standard os library

import os
with open('test.txt','w') as f:
    f.write(os.linesep)

回答 7

另外,如果您要使其成为控制台程序,则可以执行以下操作:print(" ")并继续执行程序。我发现这是分隔文本的最简单方法。

Also if you’re making it a console program, you can do: print(" ") and continue your program. I’ve found it the easiest way to separate my text.


在Python的同一行上有多个打印

问题:在Python的同一行上有多个打印

我想运行一个脚本,该脚本基本上显示如下输出:

Installing XXX...               [DONE]

目前,我Installing XXX...先打印,然后再打印[DONE]

不过,我现在想打印Installing xxx...[DONE]在同一行。

有任何想法吗?

I want to run a script, which basically shows an output like this:

Installing XXX...               [DONE]

Currently, I print Installing XXX... first and then I print [DONE].

However, I now want to print Installing xxx... and [DONE] on the same line.

Any ideas?


回答 0

您可以使用该print语句执行此操作,而无需导入sys

def install_xxx():
   print "Installing XXX...      ",

install_xxx()
print "[DONE]"

行尾的逗号会print阻止print发出新行(您应注意,输出末尾会有多余的空格)。

Python 3解决方案
由于上述内容在Python 3中不起作用,因此您可以改为这样做(同样,不导入sys):

def install_xxx():
    print("Installing XXX...      ", end="", flush=True)

install_xxx()
print("[DONE]")

打印功能接受end默认值为的参数"\n"。将其设置为空字符串可防止它在该行的末尾发出新行。

You can use the print statement to do this without importing sys.

def install_xxx():
   print "Installing XXX...      ",

install_xxx()
print "[DONE]"

The comma on the end of the print line prevents print from issuing a new line (you should note that there will be an extra space at the end of the output).

The Python 3 Solution
Since the above does not work in Python 3, you can do this instead (again, without importing sys):

def install_xxx():
    print("Installing XXX...      ", end="", flush=True)

install_xxx()
print("[DONE]")

The print function accepts an end parameter which defaults to "\n". Setting it to an empty string prevents it from issuing a new line at the end of the line.


回答 1

您可以简单地使用:

print 'something',
...
print ' else',

和输出将是

something else

无需过度杀伤import sys。注意末尾的逗号符号。

Python 3+ print("some string", end="");删除结尾处的换行符。阅读更多help(print);

You can simply use this:

print 'something',
...
print ' else',

and the output will be

something else

no need to overkill by import sys. Pay attention to comma symbol at the end.

Python 3+ print("some string", end=""); to remove the newline insert at the end. Read more by help(print);


回答 2

您应使用退格键’ \ r ‘或(’ \ x08 ‘)char返回控制台输出中的上一个位置

Python 2+:

import time
import sys

def backspace(n):
    sys.stdout.write((b'\x08' * n).decode()) # use \x08 char to go back   

for i in range(101):                        # for 0 to 100
    s = str(i) + '%'                        # string for output
    sys.stdout.write(s)                     # just print
    sys.stdout.flush()                      # needed for flush when using \x08
    backspace(len(s))                       # back n chars    
    time.sleep(0.2)                         # sleep for 200ms

Python 3:

import time   

def backline():        
    print('\r', end='')                     # use '\r' to go back


for i in range(101):                        # for 0 to 100
    s = str(i) + '%'                        # string for output
    print(s, end='')                        # just print and flush
    backline()                              # back to the beginning of line    
    time.sleep(0.2)                         # sleep for 200ms

此代码将在一行中从0%到100%计数。最终值将是:

> python test.py
100%

在这种情况下,有关刷新的其他信息在这里:为什么包含’end =’参数的python打印语句在while循环中的行为不同?

You should use backspace ‘\r‘ or (‘\x08‘) char to go back on previous position in console output

Python 2+:

import time
import sys

def backspace(n):
    sys.stdout.write((b'\x08' * n).decode()) # use \x08 char to go back   

for i in range(101):                        # for 0 to 100
    s = str(i) + '%'                        # string for output
    sys.stdout.write(s)                     # just print
    sys.stdout.flush()                      # needed for flush when using \x08
    backspace(len(s))                       # back n chars    
    time.sleep(0.2)                         # sleep for 200ms

Python 3:

import time   

def backline():        
    print('\r', end='')                     # use '\r' to go back


for i in range(101):                        # for 0 to 100
    s = str(i) + '%'                        # string for output
    print(s, end='')                        # just print and flush
    backline()                              # back to the beginning of line    
    time.sleep(0.2)                         # sleep for 200ms

This code will count from 0% to 100% on one line. Final value will be:

> python test.py
100%

Additional info about flush in this case here: Why do python print statements that contain ‘end=’ arguments behave differently in while-loops?


回答 3

使用sys.stdout.write('Installing XXX... ')sys.stdout.write('Done')。这样,"\n"如果要重新创建打印功能,则必须手动添加新行。我认为可能不必为此专门使用诅咒。

Use sys.stdout.write('Installing XXX... ') and sys.stdout.write('Done'). In this way, you have to add the new line by hand with "\n" if you want to recreate the print functionality. I think that it might be unnecessary to use curses just for this.


回答 4

没有一个答案对我有用,因为它们都暂停了,直到遇到新的一行。我写了一个简单的助手:

def print_no_newline(string):
    import sys
    sys.stdout.write(string)
    sys.stdout.flush()

要测试它:

import time
print_no_newline('hello ')
# Simulate a long task
time.sleep(2)
print('world')

“ hello”将首先打印出来,然后在睡眠前冲洗到屏幕。之后,您可以使用标准打印。

None of the answers worked for me since they all paused until a new line was encountered. I wrote a simple helper:

def print_no_newline(string):
    import sys
    sys.stdout.write(string)
    sys.stdout.flush()

To test it:

import time
print_no_newline('hello ')
# Simulate a long task
time.sleep(2)
print('world')

“hello ” will first print out and flush to the screen before the sleep. After that you can use standard print.


回答 5

sys.stdout.write 将打印而无需回车

import sys
sys.stdout.write("installing xxx")
sys.stdout.write(".")

http://en.wikibooks.org/wiki/Python_Programming/Input_and_output#printing_without_commas_or_newlines

sys.stdout.write will print without return carriage

import sys
sys.stdout.write("installing xxx")
sys.stdout.write(".")

http://en.wikibooks.org/wiki/Python_Programming/Input_and_output#printing_without_commas_or_newlines


回答 6

最简单的:

Python 3

    print('\r' + 'something to be override', end='')

这意味着它将把光标返回到开始处,而不是打印一些内容并在同一行结束。如果处于循环中,它将在开始的位置开始打印。

Most simple:

Python 3

    print('\r' + 'something to be override', end='')

It means it will back the cursor to beginning, than will print something and will end in the same line. If in a loop it will start printing in the same place it starts.


回答 7

这个简单的示例将在同一行上打印1-10。

for i in range(1,11):
    print (i, end=" ")

This simple example will print 1-10 on the same line.

for i in range(1,11):
    print (i, end=" ")

回答 8

Print有一个可选end参数,它是最终输出的内容。默认值为换行符,但您可以将其更改为空字符串。例如print("hello world!", end="")

Print has an optional end argument, it is what printed in the end. The default is a newline, but you can change it to empty string. e.g. print("hello world!", end="")


回答 9

如果你想覆盖前一行(而不是不断地增加它),你可以结合\r使用 print(),,在打印语句的结束。例如,

from time import sleep

for i in xrange(0, 10):
    print("\r{0}".format(i)),
    sleep(.5)

print("...DONE!")

将计数0到9,替换控制台中的旧数字。的"...DONE!"将打印在同一行作为最后的反击,9。

对于OP,这将允许控制台将安装的完成百分比显示为“进度条”,您可以在其中定义开始和结束字符位置,并在其间更新标记。

print("Installing |XXXXXX              | 30%"),

If you want to overwrite the previous line (rather than continually adding to it), you can combine \r with print(), at the end of the print statement. For example,

from time import sleep

for i in xrange(0, 10):
    print("\r{0}".format(i)),
    sleep(.5)

print("...DONE!")

will count 0 to 9, replacing the old number in the console. The "...DONE!" will print on the same line as the last counter, 9.

In your case for the OP, this would allow the console to display percent complete of the install as a “progress bar”, where you can define a begin and end character position, and update the markers in between.

print("Installing |XXXXXX              | 30%"),

回答 10

这里是@ Vadim-Zin4uk从3.0版本派生的2.7兼容版本:

Python 2

import time

for i in range(101):                        # for 0 to 100
    s = str(i) + '%'                        # string for output
    print '{0}\r'.format(s),                # just print and flush

    time.sleep(0.2)

为此,提供的3.0解决方案看起来有些looks肿。例如,退格方法不使用整数参数,可能完全可以使用。

Python 3

import time

for i in range(101):                        # for 0 to 100
    s = str(i) + '%'                        # string for output
    print('{0}\r'.format(s), end='')        # just print and flush

    time.sleep(0.2)                         # sleep for 200ms

两者都已经过测试和工作。

Here a 2.7-compatible version derived from the 3.0 version by @Vadim-Zin4uk:

Python 2

import time

for i in range(101):                        # for 0 to 100
    s = str(i) + '%'                        # string for output
    print '{0}\r'.format(s),                # just print and flush

    time.sleep(0.2)

For that matter, the 3.0 solution provided looks a little bloated. For example, the backspace method doesn’t make use of the integer argument and could probably be done away with altogether.

Python 3

import time

for i in range(101):                        # for 0 to 100
    s = str(i) + '%'                        # string for output
    print('{0}\r'.format(s), end='')        # just print and flush

    time.sleep(0.2)                         # sleep for 200ms

Both have been tested and work.


回答 11

这是一个非常古老的线程,但是这里有一个非常详尽的答案和示例代码。

\r是ASCII字符集的回车的字符串表示形式。与八进制015[ chr(0o15)]或十六进制0d[ chr(0x0d)]或十进制13[ chr(13)]相同。请参阅man ascii无聊的阅读。它(\r)是一种可移植的表示形式,足以让人们阅读。这很简单,就是在不推进纸张的情况下将打字机上的笔架一直移动到起点。这是CR一部分CRLF,这意味着回车和换行

print()是Python 3中的函数。在Python 2(您可能会感兴趣的任何版本)中,print可以通过从__future__模块中导入函数的定义来强制使用该函数。该print功能的好处在于,您可以指定在\n结尾处打印的内容,而不是在每次print()调用结束时打印换行符的默认行为。

sys.stdout.flush告诉Python刷新标准输出的输出,print()除非您另外指定,否则发送标准输出的位置。您还可以通过运行python -u或设置环境变量来获得相同的行为PYTHONUNBUFFERED=1,从而跳过import syssys.stdout.flush()调用。通过这样做,您获得的收益几乎完全为零,并且如果您方便地忘记了必须在应用程序正常运行之前执行该步骤,那么调试起来就不太容易。

和一个样本。请注意,这可以在Python 2或3中完美运行。

from __future__ import print_function

import sys
import time

ANS = 42
FACTORS = {n for n in range(1, ANS + 1) if ANS % n == 0}

for i in range(1, ANS + 1):
    if i in FACTORS:
        print('\r{0:d}'.format(i), end='')
        sys.stdout.flush()
        time.sleep(ANS / 100.0)
else:
    print()

This is a very old thread, but here’s a very thorough answer and sample code.

\r is the string representation of Carriage Return from the ASCII character set. It’s the same as octal 015 [chr(0o15)] or hexidecimal 0d [chr(0x0d)] or decimal 13 [chr(13)]. See man ascii for a boring read. It (\r) is a pretty portable representation and is easy enough for people to read. It very simply means to move the carriage on the typewriter all the way back to the start without advancing the paper. It’s the CR part of CRLF which means Carriage Return and Line Feed.

print() is a function in Python 3. In Python 2 (any version that you’d be interested in using), print can be forced into a function by importing its definition from the __future__ module. The benefit of the print function is that you can specify what to print at the end, overriding the default behavior of \n to print a newline at the end of every print() call.

sys.stdout.flush tells Python to flush the output of standard output, which is where you send output with print() unless you specify otherwise. You can also get the same behavior by running with python -u or setting environment variable PYTHONUNBUFFERED=1, thereby skipping the import sys and sys.stdout.flush() calls. The amount you gain by doing that is almost exactly zero and isn’t very easy to debug if you conveniently forget that you have to do that step before your application behaves properly.

And a sample. Note that this runs perfectly in Python 2 or 3.

from __future__ import print_function

import sys
import time

ANS = 42
FACTORS = {n for n in range(1, ANS + 1) if ANS % n == 0}

for i in range(1, ANS + 1):
    if i in FACTORS:
        print('\r{0:d}'.format(i), end='')
        sys.stdout.flush()
        time.sleep(ANS / 100.0)
else:
    print()

回答 12

print()具有内置参数“ end”,默认情况下设置为“ \ n”。调用print(“ This is America”)实际上是调用print(“ This is America”,end =“ \ n”)。一种简单的方法是调用print(“ This is America”,end =“”)

print() has a built in parameter “end” that is by default set to “\n” Calling print(“This is America”) is actually calling print(“This is America”, end = “\n”). An easy way to do is to call print(“This is America”, end =””)


回答 13

以防万一您已将值预先存储在数组中,可以按以下格式调用它们:

for i in range(0,n):
       print arr[i],

Just in case you have pre-stored the values in an array, you can call them in the following format:

for i in range(0,n):
       print arr[i],

回答 14

Python附加换行符作为打印结束。对于print3的python3使用end =”来添加空格而不是换行符。对于python2,请在打印语句末尾使用逗号。

print("Foo",end=' ')
print('Bar')

Python appends newline as an end to print. Use end=’ ‘ for python3 for print method to append a space instead of a newline. for python2 use comma at end of print statement.

print("Foo",end=' ')
print('Bar')


回答 15

找到此Quora帖子,并找到适用于我的示例(python 3),该示例更接近于我需要的示例(即,删除了前一行)。

他们提供的示例:

def clock():
   while True:
       print(datetime.now().strftime("%H:%M:%S"), end="\r")

如其他人所建议,要在同一行上打印,只需使用 end=""

Found this Quora post, with this example which worked for me (python 3), which was closer to what I needed it for (i.e. erasing the whole previous line).

The example they provide:

def clock():
   while True:
       print(datetime.now().strftime("%H:%M:%S"), end="\r")

For printing the on the same line, as others have suggested, just use end=""


回答 16

我找到了这个解决方案,并且可以在Python 2.7上运行

# Working on Python 2.7 Linux

import time
import sys


def backspace(n):
    print('\r', end='')                     # use '\r' to go back


for i in range(101):                        # for 0 to 100
    s = str(i) + '%'                        # string for output
    sys.stdout.write(string)
    backspace(len(s))                       # back for n chars
    sys.stdout.flush()
    time.sleep(0.2)                         # sleep for 200ms

I found this solution, and it’s working on Python 2.7

# Working on Python 2.7 Linux

import time
import sys


def backspace(n):
    print('\r', end='')                     # use '\r' to go back


for i in range(101):                        # for 0 to 100
    s = str(i) + '%'                        # string for output
    sys.stdout.write(string)
    backspace(len(s))                       # back for n chars
    sys.stdout.flush()
    time.sleep(0.2)                         # sleep for 200ms

在写入文件时,如何在Python中指定换行符?

问题:在写入文件时,如何在Python中指定换行符?

与Java(以字符串形式)相比,您可以执行"First Line\r\nSecond Line"

那么,为了在常规文件中写多行,您将如何在Python中执行此操作?

In comparison to Java (in a string), you would do something like "First Line\r\nSecond Line".

So how would you do that in Python, for purposes of writing multiple lines to a regular file?


回答 0

这取决于您想做的正确程度。\n通常会做的工作。如果您确实想解决问题,请在os包中查找换行符。(实际上称为linesep。)

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

It depends on how correct you want to be. \n will usually do the job. If you really want to get it right, you look up the newline character in the os package. (It’s actually called linesep.)

Note: when writing to files using the Python API, do not use the os.linesep. Just use \n; Python automatically translates that to the proper newline character for your platform.


回答 1

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

例:

    print('First line \n Second line') 

\n换行符在哪里。

这将产生结果:

First line
 Second line

如果使用Python 2,则不要在print函数上使用括号。

The new line character is \n. It is used inside a string.

Example:

    print('First line \n Second line') 

where \n is the newline character.

This would yield the result:

First line
 Second line

If you use Python 2, you do not use the parentheses on the print function.


回答 2

您可以分别在新行中编写,也可以在单个字符串中编写,这样更容易。

例子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

You can either write in the new lines separately or within a single string, which is easier.

Example 1

Input

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

You can write the ‘\n’ separately:

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

Output

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

Example 2

Input

As others have pointed out in the previous answers, place the \n at the relevant points in your string:

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

file.write(line)

Output

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

回答 3

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

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

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

If you are entering several lines of text at once, I find this to be the most readable format.

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

The \ at the end of each line escapes the new line (which would cause an error).


回答 4

在Python中,您只能使用换行符,即 \n

In Python you can just use the new-line character, i.e. \n


回答 5

最简单的解决方案

如果仅print不带任何参数的情况下调用,它将输出空白行。

print

您可以将输出通过管道传输到这样的文件中(考虑您的示例):

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

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

说明

print()函数在字符串的末尾有一个可选的关键字参数,称为end,默认为OS的换行符,例如。\n。因此,当您打电话时print('hello'),Python实际上正在打印'hello' + '\n'。这意味着当您print不带任何参数调用时,它实际上是print '' + '\n',这导致换行符。

另类

使用多行字符串。

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

Simplest solution

If you only call print without any arguments, it will output a blank line.

print

You can pipe the output to a file like this (considering your example):

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

Not only is it OS-agnostic (without even having to use the os package), it’s also more readable than putting \n within strings.

Explanation

The print() function has an optional keyword argument for the end of the string, called end, which defaults to the OS’s newline character, for eg. \n. So, when you’re calling print('hello'), Python is actually printing 'hello' + '\n'. Which means that when you’re calling just print without any arguments, it’s actually printing '' + '\n', which results in a newline.

Alternative

Use multi-line strings.

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

回答 6

独立于平台的断线器:Linux,Windows和IOS

import os
keyword = 'physical'+ os.linesep + 'distancing'
print(keyword)

输出:

physical
distancing

Platform independent line breaker: Linux,windows & IOS

import os
keyword = 'physical'+ os.linesep + 'distancing'
print(keyword)

Output:

physical
distancing

回答 7

与相同的方法'\n',尽管您可能不需要'\r'。您是否有理由在Java版本中使用它?如果确实需要/想要它,您也可以在Python中以相同的方式使用它。

The same way with '\n', though you’d probably not need the '\r'. Is there a reason you have it in your Java version? If you do need/want it, you can use it in the same way in Python too.


回答 8

\ 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.....

\n – simple newline character insertion works:

# 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.....

回答 9

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

Most escape characters in string literals from Java are also valid in Python, such as “\r” and “\n”.


回答 10

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

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

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

将会输出:

line1
line2
line3

这样,它可以执行任务,并且还可以使代码具有较高的可读性:)

As mentioned in other answers: “The new line character is \n. It is used inside a string”.

I found the most simple and readable way is to use the “format” function, using nl as the name for a new line, and break the string you want to print to the exact format you going to print it:

python2:

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

python3:

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

That will output:

line1
line2
line3

This way it performs the task, and also gives high readability of the code :)


回答 11

\ 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()

\n separates the lines of a string. In the following example, I keep writing the records in a loop. Each record is separated by \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

值得注意的是,当您使用交互式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!

Worth noting that when you inspect a string using the interactive python shell or a Jupyter notebook, the \n and other backslashed strings like \t are rendered literally:

>>> 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!'

The newlines, tabs, and other special non-printed characters are rendered as whitespace only when printed, or written to a file:

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

如何读取没有换行符的文件?

问题:如何读取没有换行符的文件?

在Python中,调用

temp = open(filename,'r').readlines()

产生一个列表,其中每个元素都是文件中的一行。这有点愚蠢,但是仍然:readlines()还向每个元素写入换行符,这是我不希望发生的事情。

我该如何避免呢?

In Python, calling

temp = open(filename,'r').readlines()

results in a list in which each element is a line in the file. It’s a little stupid but still: readlines() also writes newline character to each element, something I do not wish to happen.

How can I avoid it?


回答 0

您可以使用读取整个文件并分割行str.splitlines

temp = file.read().splitlines()

或者,您可以手动删除换行符:

temp = [line[:-1] for line in file]

注意:仅当文件以换行符结尾时,后一种解决方案才有效,否则最后一行将丢失字符。

在大多数情况下,此假设是正确的(尤其是对于文本编辑器创建的文件,无论如何,它们通常都会添加结尾换行符)。

如果要避免这种情况,可以在文件末尾添加换行符:

with open(the_file, 'r+') as f:
    f.seek(-1, 2)  # go at the end of the file
    if f.read(1) != '\n':
        # add missing newline if not already present
        f.write('\n')
        f.flush()
        f.seek(0)
    lines = [line[:-1] for line in f]

或更简单的替代方法是strip换行符:

[line.rstrip('\n') for line in file]

甚至,尽管很难理解:

[line[:-(line[-1] == '\n') or len(line)+1] for line in file]

这利用了以下事实:的返回值or不是布尔值,而是被评估为true或false的对象。


readlines方法实际上等效于:

def readlines(self):
    lines = []
    for line in iter(self.readline, ''):
        lines.append(line)
    return lines

# or equivalently

def readlines(self):
    lines = []
    while True:
        line = self.readline()
        if not line:
            break
        lines.append(line)
    return lines

因为readline()保留换行符也readlines()保留它。

注意:为了readlines()使writelines()方法对称,不会添加结尾换行符,因此f2.writelines(f.readlines())会生成fin 的精确副本f2

You can read the whole file and split lines using str.splitlines:

temp = file.read().splitlines()

Or you can strip the newline by hand:

temp = [line[:-1] for line in file]

Note: this last solution only works if the file ends with a newline, otherwise the last line will lose a character.

This assumption is true in most cases (especially for files created by text editors, which often do add an ending newline anyway).

If you want to avoid this you can add a newline at the end of file:

with open(the_file, 'r+') as f:
    f.seek(-1, 2)  # go at the end of the file
    if f.read(1) != '\n':
        # add missing newline if not already present
        f.write('\n')
        f.flush()
        f.seek(0)
    lines = [line[:-1] for line in f]

Or a simpler alternative is to strip the newline instead:

[line.rstrip('\n') for line in file]

Or even, although pretty unreadable:

[line[:-(line[-1] == '\n') or len(line)+1] for line in file]

Which exploits the fact that the return value of or isn’t a boolean, but the object that was evaluated true or false.


The readlines method is actually equivalent to:

def readlines(self):
    lines = []
    for line in iter(self.readline, ''):
        lines.append(line)
    return lines

# or equivalently

def readlines(self):
    lines = []
    while True:
        line = self.readline()
        if not line:
            break
        lines.append(line)
    return lines

Since readline() keeps the newline also readlines() keeps it.

Note: for symmetry to readlines() the writelines() method does not add ending newlines, so f2.writelines(f.readlines()) produces an exact copy of f in f2.


回答 1

temp = open(filename,'r').read().split('\n')
temp = open(filename,'r').read().split('\n')

回答 2

另一个例子:

一次读取文件。从字符串结尾删除不需要的字符str.rstrip(chars)

with open(filename, 'r') as fileobj:
    for row in fileobj:
        print( row.rstrip('\n') )

又见str.strip([chars])str.lstrip([chars])

(python> = 2.0)

another example:

Reading file one row at the time. Removing unwanted chars with from end of the string str.rstrip(chars)

with open(filename, 'r') as fileobj:
    for row in fileobj:
        print( row.rstrip('\n') )

see also str.strip([chars]) and str.lstrip([chars])

(python >= 2.0)


回答 3

temp = open(filename,'r').read().splitlines()
temp = open(filename,'r').read().splitlines()

回答 4

我认为这是最好的选择。

temp = [line.strip() for line in file.readlines()]

I think this is the best option.

temp = [line.strip() for line in file.readlines()]

回答 5

尝试这个:

u=open("url.txt","r")  
url=u.read().replace('\n','')  
print(url)  

Try this:

u=open("url.txt","r")  
url=u.read().replace('\n','')  
print(url)  

回答 6

my_file = open("first_file.txt", "r")
for line in my_file.readlines():
    if line[-1:] == "\n":
        print(line[:-1])
    else:
        print(line)
my_file.close() 
my_file = open("first_file.txt", "r")
for line in my_file.readlines():
    if line[-1:] == "\n":
        print(line[:-1])
    else:
        print(line)
my_file.close() 

回答 7

import csv

with open(filename) as f:
    csvreader = csv.reader(f)
    for line in csvreader:
         print(line[0])
import csv

with open(filename) as f:
    csvreader = csv.reader(f)
    for line in csvreader:
         print(line[0])

回答 8

def getText():
    file=open("ex1.txt","r");

    names=file.read().split("\n");
    for x,word in enumerate(names):
        if(len(word)>=20):
            return 0;
            print "length of ",word,"is over 20"
            break;
        if(x==20):
            return 0;
            break;
    else:
        return names;


def show(names):
    for word in names:
        len_set=len(set(word))
        print word," ",len_set


for i in range(1):

    names=getText();
    if(names!=0):
        show(names);
    else:
        break;
def getText():
    file=open("ex1.txt","r");

    names=file.read().split("\n");
    for x,word in enumerate(names):
        if(len(word)>=20):
            return 0;
            print "length of ",word,"is over 20"
            break;
        if(x==20):
            return 0;
            break;
    else:
        return names;


def show(names):
    for word in names:
        len_set=len(set(word))
        print word," ",len_set


for i in range(1):

    names=getText();
    if(names!=0):
        show(names);
    else:
        break;

如何在Python中进行换行(换行)?

问题:如何在Python中进行换行(换行)?

我有一长行代码,我想在多行中分解。我使用什么,语法是什么?

例如,添加一串字符串,

e = 'a' + 'b' + 'c' + 'd'

并分成两行,如下所示:

e = 'a' + 'b' +
    'c' + 'd'

I have a long line of code that I want to break up among multiple lines. What do I use and what is the syntax?

For example, adding a bunch of strings,

e = 'a' + 'b' + 'c' + 'd'

and have it in two lines like this:

e = 'a' + 'b' +
    'c' + 'd'

回答 0

什么线?您只需在下一行就有参数就不会有任何问题:

a = dostuff(blahblah1, blahblah2, blahblah3, blahblah4, blahblah5, 
            blahblah6, blahblah7)

否则,您可以执行以下操作:

if a == True and \
   b == False

查看样式指南以获取更多信息。

从示例行中:

a = '1' + '2' + '3' + \
    '4' + '5'

要么:

a = ('1' + '2' + '3' +
    '4' + '5')

请注意,样式指南指出,最好使用带括号的隐式连续符,但是在这种特殊情况下,仅在表达式周围加上括号可能是错误的方法。

What is the line? You can just have arguments on the next line without any problems:

a = dostuff(blahblah1, blahblah2, blahblah3, blahblah4, blahblah5, 
            blahblah6, blahblah7)

Otherwise you can do something like this:

if a == True and \
   b == False

Check the style guide for more information.

From your example line:

a = '1' + '2' + '3' + \
    '4' + '5'

Or:

a = ('1' + '2' + '3' +
    '4' + '5')

Note that the style guide says that using the implicit continuation with parentheses is preferred, but in this particular case just adding parentheses around your expression is probably the wrong way to go.


回答 1

PEP 8-Python代码样式指南

包装长行的首选方法是在括号,方括号和花括号内使用Python的隐含行连续性。通过将表达式包装在括号中,可以将长行分成多行。应优先使用这些,而不是使用反斜杠进行行连续。

有时反斜杠可能仍然合适。例如,长的多个with语句不能使用隐式连续,因此可以使用反斜杠:

with open('/path/to/some/file/you/want/to/read') as file_1, \
        open('/path/to/some/file/being/written', 'w') as file_2:
    file_2.write(file_1.read())

另一种此类情况是使用assert语句。

确保适当缩进续行。绕开二元运算符的首选位置是运算符之后,而不是在运算符之前。一些例子:

class Rectangle(Blob):

    def __init__(self, width, height,
                 color='black', emphasis=None, highlight=0):
        if (width == 0 and height == 0 and
                color == 'red' and emphasis == 'strong' or
                highlight > 100):
            raise ValueError("sorry, you lose")
        if width == 0 and height == 0 and (color == 'red' or
                                           emphasis is None):
            raise ValueError("I don't think so -- values are %s, %s" %
                             (width, height))
        Blob.__init__(self, width, height,
                      color, emphasis, highlight)

现在,PEP8建议数学家及其发布者使用相反的约定(用于在二进制运算处中断)以提高可读性。

唐纳德·克努斯(Donald Knuth)二元运算符垂直对齐之前先断后合的风格,从而减少了确定要添加和减去的项时的工作量。

PEP8:换行符应该在二进制运算符之前还是之后?

唐纳德·克努斯(Donald Knuth)在他的《计算机和排版》系列中解释了传统规则:“尽管段落中的公式总是在二进制运算和关系之后中断,但显示的公式总是在二进制运算和关系之前中断” [3]。

遵循数学的传统通常会导致代码更具可读性:

# Yes: easy to match operators with operands
income = (gross_wages
          + taxable_interest
          + (dividends - qualified_dividends)
          - ira_deduction
          - student_loan_interest)

在Python代码中,只要约定在本地是一致的,就可以在二进制运算符之前或之后中断。对于新代码,建议使用Knuth的样式。

[3]:Donald Knuth的The TeXBook,第195和196页

From PEP 8 — Style Guide for Python Code:

The preferred way of wrapping long lines is by using Python’s implied line continuation inside parentheses, brackets and braces. Long lines can be broken over multiple lines by wrapping expressions in parentheses. These should be used in preference to using a backslash for line continuation.

Backslashes may still be appropriate at times. For example, long, multiple with-statements cannot use implicit continuation, so backslashes are acceptable:

with open('/path/to/some/file/you/want/to/read') as file_1, \
        open('/path/to/some/file/being/written', 'w') as file_2:
    file_2.write(file_1.read())

Another such case is with assert statements.

Make sure to indent the continued line appropriately. The preferred place to break around a binary operator is after the operator, not before it. Some examples:

class Rectangle(Blob):

    def __init__(self, width, height,
                 color='black', emphasis=None, highlight=0):
        if (width == 0 and height == 0 and
                color == 'red' and emphasis == 'strong' or
                highlight > 100):
            raise ValueError("sorry, you lose")
        if width == 0 and height == 0 and (color == 'red' or
                                           emphasis is None):
            raise ValueError("I don't think so -- values are %s, %s" %
                             (width, height))
        Blob.__init__(self, width, height,
                      color, emphasis, highlight)

PEP8 now recommends the opposite convention (for breaking at binary operations) used by mathematicians and their publishers to improve readability.

Donald Knuth’s style of breaking before a binary operator aligns operators vertically, thus reducing the eye’s workload when determining which items are added and subtracted.

From PEP8: Should a line break before or after a binary operator?:

Donald Knuth explains the traditional rule in his Computers and Typesetting series: “Although formulas within a paragraph always break after binary operations and relations, displayed formulas always break before binary operations”[3].

Following the tradition from mathematics usually results in more readable code:

# Yes: easy to match operators with operands
income = (gross_wages
          + taxable_interest
          + (dividends - qualified_dividends)
          - ira_deduction
          - student_loan_interest)

In Python code, it is permissible to break before or after a binary operator, as long as the convention is consistent locally. For new code Knuth’s style is suggested.

[3]: Donald Knuth’s The TeXBook, pages 195 and 196


回答 2

使用反斜杠结束行的危险在于,如果在反斜杠之后添加空格(当然很难看到),则反斜杠将不再执行您原本的想法。

有关更多信息,请参见Python习语和反习语(对于Python 2Python 3)。

The danger in using a backslash to end a line is that if whitespace is added after the backslash (which, of course, is very hard to see), the backslash is no longer doing what you thought it was.

See Python Idioms and Anti-Idioms (for Python 2 or Python 3) for more.


回答 3

\在行末放置a 或将语句括在parens中( .. )。从IBM

b = ((i1 < 20) and
     (i2 < 30) and
     (i3 < 40))

要么

b = (i1 < 20) and \
    (i2 < 30) and \
    (i3 < 40)

Put a \ at the end of your line or enclose the statement in parens ( .. ). From IBM:

b = ((i1 < 20) and
     (i2 < 30) and
     (i3 < 40))

or

b = (i1 < 20) and \
    (i2 < 30) and \
    (i3 < 40)

回答 4

您可以在括号和大括号之间打断线。此外,您可以将反斜杠字符附加\到一行以显式中断它:

x = (tuples_first_value,
     second_value)
y = 1 + \
    2

You can break lines in between parenthesises and braces. Additionally, you can append the backslash character \ to a line to explicitly break it:

x = (tuples_first_value,
     second_value)
y = 1 + \
    2

回答 5

从马口中:显式线连接

可以使用反斜杠字符(\)将两条或更多条物理行连接为逻辑行,如下所示:当一条物理行以不属于字符串文字或注释的反斜杠结尾时,则将其与以下行合并成一条逻辑行,删除反斜杠和以下换行符。例如:

if 1900 < year < 2100 and 1 <= month <= 12 \
   and 1 <= day <= 31 and 0 <= hour < 24 \
   and 0 <= minute < 60 and 0 <= second < 60:   # Looks like a valid date
        return 1

以反斜杠结尾的行不能带有注释。反斜杠不会继续发表评论。除字符串文字外,反斜杠不会延续令牌(即,字符串文字之外的令牌无法使用反斜杠在物理行之间进行拆分)。反斜杠在字符串文字之外的其他行上是非法的。

From the horse’s mouth: Explicit line joining

Two or more physical lines may be joined into logical lines using backslash characters (\), as follows: when a physical line ends in a backslash that is not part of a string literal or comment, it is joined with the following forming a single logical line, deleting the backslash and the following end-of-line character. For example:

if 1900 < year < 2100 and 1 <= month <= 12 \
   and 1 <= day <= 31 and 0 <= hour < 24 \
   and 0 <= minute < 60 and 0 <= second < 60:   # Looks like a valid date
        return 1

A line ending in a backslash cannot carry a comment. A backslash does not continue a comment. A backslash does not continue a token except for string literals (i.e., tokens other than string literals cannot be split across physical lines using a backslash). A backslash is illegal elsewhere on a line outside a string literal.


回答 6

这可能不是Python的方式,但是我通常使用带有join函数的列表来编写长字符串,例如SQL查询:

query = " ".join([
    'SELECT * FROM "TableName"',
    'WHERE "SomeColumn1"=VALUE',
    'ORDER BY "SomeColumn2"',
    'LIMIT 5;'
])

It may not be the Pythonic way, but I generally use a list with the join function for writing a long string, like SQL queries:

query = " ".join([
    'SELECT * FROM "TableName"',
    'WHERE "SomeColumn1"=VALUE',
    'ORDER BY "SomeColumn2"',
    'LIMIT 5;'
])

回答 7

摘自《 The Hitchhiker’s Guide to Python(Line Continuation)》:

当逻辑代码行长于可接受的限制时,您需要将其划分为多条物理行。如果该行的最后符是反斜杠,则Python解释器将连接连续的行。在某些情况下这很有用,但由于其易碎性通常应避免使用:在反斜杠后的行末添加空格将破坏代码并可能产生意外结果。

更好的解决方案是在元素周围使用括号。在行尾留下未封闭的括号的情况下,Python解释器将加入下一行,直到括号被封闭为止。花括号和方括号的行为相同。

但是,通常情况下,必须分开一条较长的逻辑线表明您正在尝试同时执行太多操作,这可能会影响可读性。

话虽如此,这是一个考虑多次导入的示例(当超出行限制时,在PEP-8上定义),通常也适用于字符串:

from app import (
    app, abort, make_response, redirect, render_template, request, session
)

Taken from The Hitchhiker’s Guide to Python (Line Continuation):

When a logical line of code is longer than the accepted limit, you need to split it over multiple physical lines. The Python interpreter will join consecutive lines if the last character of the line is a backslash. This is helpful in some cases, but should usually be avoided because of its fragility: a white space added to the end of the line, after the backslash, will break the code and may have unexpected results.

A better solution is to use parentheses around your elements. Left with an unclosed parenthesis on an end-of-line the Python interpreter will join the next line until the parentheses are closed. The same behaviour holds for curly and square braces.

However, more often than not, having to split a long logical line is a sign that you are trying to do too many things at the same time, which may hinder readability.

Having that said, here’s an example considering multiple imports (when exceeding line limits, defined on PEP-8), also applied to strings in general:

from app import (
    app, abort, make_response, redirect, render_template, request, session
)

回答 8

如果由于长字符串而要中断行,可以将该字符串分成几部分:

long_string = "a very long string"
print("a very long string")

将被替换

long_string = (
  "a "
  "very "
  "long "
  "string"
)
print(
  "a "
  "very "
  "long "
  "string"
)

两个打印语句的输出:

a very long string

注意情感中的括号。

还要注意,将文字字符串分成几部分,只允许在部分字符串上使用文字前缀:

s = (
  "2+2="
  f"{2+2}"
)

If you want to break your line because of a long literal string, you can break that string into pieces:

long_string = "a very long string"
print("a very long string")

will be replaced by

long_string = (
  "a "
  "very "
  "long "
  "string"
)
print(
  "a "
  "very "
  "long "
  "string"
)

Output for both print statements:

a very long string

Notice the parenthesis in the affectation.

Notice also that breaking literal strings into pieces allows to use the literal prefix only on parts of the string:

s = (
  "2+2="
  f"{2+2}"
)

回答 9

使用行继续运算符,即“ \”

例子:

# Ex.1

x = 1
s =  x + x**2/2 + x**3/3 \
       + x**4/4 + x**5/5 \
       + x**6/6 + x**7/7 \
       + x**8/8
print(s)
# 2.7178571428571425


----------


# Ex.2

text = ('Put several strings within parentheses ' \
        'to have them joined together.')
print(text)


----------


# Ex.3

x = 1
s =  x + x**2/2 \
       + x**3/3 \
       + x**4/4 \
       + x**6/6 \
       + x**8/8
print(s)
# 2.3749999999999996

Use the line continuation operator i.e. “\”

Examples:

# Ex.1

x = 1
s =  x + x**2/2 + x**3/3 \
       + x**4/4 + x**5/5 \
       + x**6/6 + x**7/7 \
       + x**8/8
print(s)
# 2.7178571428571425


----------


# Ex.2

text = ('Put several strings within parentheses ' \
        'to have them joined together.')
print(text)


----------


# Ex.3

x = 1
s =  x + x**2/2 \
       + x**3/3 \
       + x**4/4 \
       + x**6/6 \
       + x**8/8
print(s)
# 2.3749999999999996