How to print a linebreak in a python function?

PythonLine Breaks

Python Problem Overview


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.

Python Solutions


Solution 1 - Python

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

Solution 2 - Python

The newline character is actually '\n'.

Solution 3 - Python

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

Solution 4 - Python

All three way you can use for newline character :

'\n'

"\n"

"""\n"""

Solution 5 - Python

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

Solution 6 - Python

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

Solution 7 - Python

You can print a native linebreak using the standard os library

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

Solution 8 - Python

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.

Solution 9 - Python

A = ['a1', 'a2', 'a3'] 
B = ['b1', 'b2', 'b3']
for a,b in zip(A,B): 
    print(f">{a}\n{b}")

Below python 3.6 instead of print(f">{a}\n{b}") use print(">%s\n%s" % (a, b))

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionGeparadaView Question on Stackoverflow
Solution 1 - PythonWinston EwertView Answer on Stackoverflow
Solution 2 - PythonzeekayView Answer on Stackoverflow
Solution 3 - PythonTrufaView Answer on Stackoverflow
Solution 4 - PythonVarun KumarView Answer on Stackoverflow
Solution 5 - PythoninspectorG4dgetView Answer on Stackoverflow
Solution 6 - Pythonuser6536489View Answer on Stackoverflow
Solution 7 - PythonphilshemView Answer on Stackoverflow
Solution 8 - PythonINfoUpgradersView Answer on Stackoverflow
Solution 9 - PythonsilgonView Answer on Stackoverflow