Python中print()函数不换行的方法

一、让print()函数不换行

  在Python中,print()函数默认是换行的。但是,在很多情况下,我们需要不换行的输出(比如在算法竞赛中)。那么,在Python中如何做到这一点呢?

  其实很简单。只要指定print()函数的end参数为空就可以了。(默认是’ ’)

  例如:

1 print('hello world', end='')
2 print('!!!')

  输出为:Python中print()函数不换行的方法

二、print()函数浅析

  当然,print()函数不止有end这个参数,还有其它几个参数。下面我们来看一看这些参数对输出分别起到什么作用。

  先来看一下print()函数的原型:

print(*objectssep='  'end=' 'file=sys.stdoutflush=False)

  以下摘自官方文档:

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

All non-keyword arguments are converted to strings like str() does and written to the stream, separated by sep and followed by end. Both sep and end must be strings; they can also be None, which means to use the default values. If no objects are given, print() will just write end.

The file argument must be an object with a write(string) method; if it is not present or None, sys.stdout will be used. Since printed arguments are converted to text strings, print() cannot be used with binary mode file objects. For these, use file.write(...) instead.

Whether output is buffered is usually determined by file, but if the flush keyword argument is true, the stream is forcibly flushed.

Changed in version 3.3: Added the flush keyword argument.

  也就是说,print()将objects转换成strings输出到流中,用sep分隔,以end结束。

  下面通过几个例子,来具体的看一看print()函数各参数的作用。

  第一个参数objects就不多说了,要是不知道干啥的可以考虑从头学起。

  第二个参数sep,表示objects参数连接时使用的字符,默认是空格。

1 print('hello', 'world', sep='*')

  输出为:Python中print()函数不换行的方法

  第三个参数end,表示输出完后的结束符,默认是换行。例子前面有了。

  第四个参数file,表示输出到哪里,默认是sys.stdout。必须是file-like对象,即有write方法,不可以用二进制模式。

1 f = open('print.txt', 'w')
2 print('hello', 'world', file=f)

  程序运行结束后,打开文件可以看到:Python中print()函数不换行的方法

  第五个参数flush,表示是否立即输出到file所指定的对象中。当为True时,立即输出,当为False时,则取决于file对象(一般是不立即输出)。

  上面的例子,如果加个暂停,可以发现,数据没有被立即写入,只有在f.close()后才被写入。如果没有写f.close(),那就在程序运行结束以后写入。

1 f = open('print.txt', 'w')
2 print('hello', 'world', file=f)
3 s = input('f.close()? (Y/N)')
4 if s == 'Y':
5     f.close()

  如果flush为True时,则会被立即写入。

1 f = open('print.txt', 'w')
2 print('hello', 'world', file=f, flush=True)
3 s = input('f.close()? (Y/N)')
4 if s == 'Y':
5     f.close()

  以上就是对Python中print()函数的浅析,鉴于本人的水平有限,有不妥之处,还请指出。

 1 #!/usr/bin/env python3
 2 # -*- coding: utf-8 -*-
 3 
 4 # 不换行
 5 print('hello world', end='')
 6 print('!!!')
 7 
 8 f = open('print.txt', 'w')
 9 f1 = open('print1.txt', 'w')
10 
11 print('hello', 'world')
12 print('hello', 'world', sep='*')
13 print('hello', 'world', file=f)
14 print('hello', 'world', file=f1, flush=True)
15 
16 s = input('f.close()? (Y/N)')
17 if s == 'Y':
18     f.close()
19 
20 # 如果输入为N,此处暂停观察print.txt中的内容是否为空
21 s = input()