Python 的 print("msg") 是先将 "msg"+"\n"再输出还是先输出 "msg" 再输出 "\n"

今天分析 input 和 print 这俩方法的运行过程时产生一个疑问,如果我们要使用 print("msg") 输出内容,print 方法是先将 "msg" 和 "\n" 进行拼接后再调用 sys.stdout.print() 输出,还是分别输出 'msg" 和 "\n" ?

好家伙,我还特意去看了一遍源码,结论是分别输出。

分别输出。

"""
The following is from file: builtins.py
"""

# encoding: utf-8
# module builtins
# from (built-in)
# by generator 1.147
"""
Built-in functions, exceptions, and other objects.

Noteworthy: None is the `nil' object; Ellipsis represents `...' in slices.
"""


def print(self, *args, sep=' ', end='\n', file=None): # known special case of print
    """
    print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False)
    
    Prints the values to a stream, or to sys.stdout by default.
    Optional keyword arguments:
    file:  a file-like object (stream); defaults to the current sys.stdout.
    sep:   string inserted between values, default a space.
    end:   string appended after the last value, default a newline.
    flush: whether to forcibly flush the stream.
    """
    pass

 

print('msg') = print('msg',end='\n')
其实就是end默认参数是换行符,你完全可以调整end达到输出格式要求