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:58

Greg is right-- you can use sys.stdout.write

Perhaps, though, you should consider refactoring your algorithm to accumulate a list of <whatevers> and then

lst = ['h', 'm']
print  "".join(lst)
查看更多
梦该遗忘
3楼-- · 2018-12-31 08:58

I had the same problem once I wanted to read some digits from a file. I solved it like this:

f = open('file.txt', 'r')
for line in f:   
    print(str.split(line)[0])
查看更多
人间绝色
4楼-- · 2018-12-31 08:59

This may look stupid, but seems to be the simplest:

    print 'h',
    print '\bm'
查看更多
琉璃瓶的回忆
5楼-- · 2018-12-31 09:00

Just a comment. In Python 3, you will use

print('h', end='')

to suppress the endline terminator, and

print('a', 'b', 'c', sep='')

to suppress the whitespace separator between items.

查看更多
无与为乐者.
6楼-- · 2018-12-31 09:03
import sys
a=raw_input()
for i in range(0,len(a)):
       sys.stdout.write(a[i])
查看更多
临风纵饮
7楼-- · 2018-12-31 09:04

You can use:

sys.stdout.write('h')
sys.stdout.write('m')
查看更多
登录 后发表回答