End line '\n' issue in python

时间:2018-02-03 10:57:39

标签: python python-3.x

I could see a space popping up by default if I use '\n' in python 3x. Could someone please help me in removing it?

Appreciate your help in advance!

sample code:

a='How are you?'
print("Hello, World.\n",a)

Output

Hello, World.
 How are you?

Explanation

The second line of the output starts with a space. Why is this happening?

7 个答案:

答案 0 :(得分:4)

By consulting the documentation: https://docs.python.org/3.0/whatsnew/3.0.html#print-is-a-function

You can see that in Python3 the print function uses a space separator to print the arguments passed to it.

To change this behavior you can use print as:

print("Hello, World.\n", a, sep="")

答案 1 :(得分:1)

The comma adds in the space. There is a difference in-between:

print(a, b)

and

print(a+b)

Cheers, Sebastian

答案 2 :(得分:0)

printseparates its arguments by spaces. You may use two prints and omit the explicit newline \n:

print("Hello, World.")
print(a)

or you concatenate the strings:

print("Hello, World.\n" + a)

or you use a format

print("Hello, World.\n%s" % a)

答案 3 :(得分:0)

Comma is creating space replce it as

a='How are you?'
print("Hello, World.\n"+a)

答案 4 :(得分:0)

The comma is causing the space. Use the + sign to concatenate like this:

a='How are you?'
print("Hello, World.\n" + a)

outputs:

Hello, World.
How are you?

答案 5 :(得分:-1)

As stated in the Python3 documentation, the print() function does as follows:

Print objects to the text stream file, separated by sep and followed by end. sep, >end, file and flush, if present, must be given as keyword arguments.

Therefore, there's a number of ways to solve your issue:
1. Use the sep keyword argument, removing the default space separator.

a='How are you?'
print("Hello, World.\n", a, sep='')

2. Use the .format() function.

a='How are you?'
print("Hello, World.\n{}".format(a))

3. Use two print statements.

a='How are you?'
print("Hello, World.")
print(a)

All of these options will output:

Hello, World.
How are you?

Although all three are valid implementations, I'd personally choose option two as I feel it's a cleaner and more logical solution.

Hope this helps!

答案 6 :(得分:-1)

您在变量之间使用逗号分隔符。 ("string1","string2")默认情况下有空格分隔符。建议的方法是:

  1. 使用sepprint("Hello, World.\n", a, sep="")

  2. 使用+代替,print("Hello, World.\n" + a)