114

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.

1
  • 2
    Use \n. That was the issue
    – Trooper Z
    Jul 6, 2018 at 17:41

9 Answers 9

264

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

12
  • 12
    Backward slash = "\" , forward slash = "/". The OP has his slash forwards. Mar 1, 2016 at 17:51
  • 13
    @user3527975, I mean backwards in the sense of reversed from how it should be. Mar 1, 2016 at 17:52
  • 3
    since there is some confusion: @Geparda use the other slash :)
    – rsm
    Jan 21, 2017 at 7:03
  • 2
    @WinstonEwert Don't you think you should rephrase it to avoid the confusion, instead of leaving it as is? Jul 17, 2018 at 17:39
  • 9
    @LucaBezerra, there isn't any evidence that anyone was confused, just that some people are pedantic. Jul 18, 2018 at 15:09
37

The newline character is actually '\n'.

0
12

All three way you can use for newline character :

'\n'

"\n"

"""\n"""
1
11
>>> 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!

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

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

2

You can print a native linebreak using the standard os library

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

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.

1
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))

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.