Python3中的print函數

Python3中的輸出語句:

函數原型如下:
print(help(print))  使用此語句打印


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.

sep

分割符,默認爲空格

end

結尾的結束符,默認爲新行

file

輸出流,默認爲標準輸出流

flush

是否刷新輸出緩衝區

分隔符:

a = 'hello'
b = 'Python'
c = 'ixusy88'

# 默認空格
print('1----',a,b,c)

# 指定分割符
print('2----',a,b,c,sep='!')

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

"""
輸出結果:
1---- hello Python ixusy88
2----!hello!Python!ixusy88
3----,hello,Python,ixusy88
"""

end:

a = 'hello'
b = 'Python'
c = 'ixusy88'

# end 默認是新的一行,即下一個打印會在新的一行輸出
print('1----',a,b,c)

# 指定結束符,
print('2----',a,b,c,end='###')
print('3----',a,b,c)
print('4----',a,b,c)

"""
結果:
1---- hello Python ixusy88
2---- hello Python ixusy88###3---- hello Python ixusy88
4---- hello Python ixusy88
"""

輸出流:

a = 'hello'
b = 'Python'
c = 'ixusy88'

# file ,默認是sys.stdout
print('1----',a,b,c)

# file,指定輸出流,輸出到文件中
print('2----',a,b,c,file=open('test.txt','w'))
print('-1--')
# 讀取文件,並打印出來
print(open('test.txt').read() )
print('-2--')

# 也可以修改sys.stdout,把定向到一個文件,之後的所有輸出都會保存到文件中;
import sys
print('sys.stdout之後')
sys.stdout = open('test_2.txt','w')
print('1----',a,b,c)
print(sys.platform)


"""
輸出結果:
1---- hello Python ixusy88
-1--
2---- hello Python ixusy88

-2--
sys.stdout之後
"""

輸出文件中的內容

 

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章