How do I keep Python print from adding newlines or

2018-12-31 08:38发布

This question already has an answer here:

In python, if I say

print 'h'

I get the letter h and a newline. If I say

print 'h',

I get the letter h and no newline. If I say

print 'h',
print 'm',

I get the letter h, a space, and the letter m. How can I prevent Python from printing the space?

The print statements are different iterations of the same loop so I can't just use the + operator.

16条回答
弹指情弦暗扣
2楼-- · 2018-12-31 08:48
print("{0}{1}{2}".format(a, b, c))
查看更多
倾城一夜雪
3楼-- · 2018-12-31 08:49

sys.stdout.write is (in Python 2) the only robust solution. Python 2 printing is insane. Consider this code:

print "a",
print "b",

This will print a b, leading you to suspect that it is printing a trailing space. But this is not correct. Try this instead:

print "a",
sys.stdout.write("0")
print "b",

This will print a0b. How do you explain that? Where have the spaces gone?

I still can't quite make out what's really going on here. Could somebody look over my best guess:

My attempt at deducing the rules when you have a trailing , on your print:

First, let's assume that print , (in Python 2) doesn't print any whitespace (spaces nor newlines).

Python 2 does, however, pay attention to how you are printing - are you using print, or sys.stdout.write, or something else? If you make two consecutive calls to print, then Python will insist on putting in a space in between the two.

查看更多
君临天下
4楼-- · 2018-12-31 08:51
print('''first line \
second line''')

it will produce

first line second line

查看更多
倾城一夜雪
5楼-- · 2018-12-31 08:52

For completeness, one other way is to clear the softspace value after performing the write.

import sys
print "hello",
sys.stdout.softspace=0
print "world",
print "!"

prints helloworld !

Using stdout.write() is probably more convenient for most cases though.

查看更多
一个人的天荒地老
6楼-- · 2018-12-31 08:52

I am not adding a new answer. I am just putting the best marked answer in a better format. I can see that the best answer by rating is using sys.stdout.write(someString). You can try this out:

    import sys
    Print = sys.stdout.write
    Print("Hello")
    Print("World")

will yield:

HelloWorld

That is all.

查看更多
萌妹纸的霸气范
7楼-- · 2018-12-31 08:56

You can use print like the printf function in C.

e.g.

print "%s%s" % (x, y)

查看更多
登录 后发表回答