问题:如何在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.


声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。