Python?2.x 系列已經停止維護了, python? 3.x 系列正在成為主流,盡管有些項目還是python2.x 的,之后寫Python?代碼為了保持兼容性,還是盡量和Python?3 標準保持一致
作為一個Python?newbee 而言, python 2.x 和 3.x 的 最大的區別就是 print 從一個命令 變成了一個函數, raw_input() 被 input() 取而代之
Python?最好的地方 之一就是文檔很齊全,https://docs.python.org/3/? 學習 python的好去處
下方是 從命令行中 使用 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.
1. print 函數的格式化輸出
1.1 符號占位符
print("{name} is {age} years old.".format(name = "jack", age = 23)
1.2 類似于C語言的占位符
print("%s is %d years old." % ("jack", 23))
2. print 函數重定向標準輸出到文件
def write_log(string, file_name):
try:
with open(file_name, 'a') as log_file:
print(string, file = log_file)
log_file.close()
except OSError as exc:
tb = sys.exc_info()[-1]
lineno = tb.tb_lineno
filename = tb.tb_frame.f_code.co_filename
print('{} at {} line {}.'.format(exc.strerror, filename, lineno))
sys.exit(exc.errno)
def main():
write_log("hello log!", "journal.txt")
if __name__ == '__main__':
main()
3. print 打印當前系統時間精確到毫秒, 需要導入時間包, 下方的代碼參考 stackflow.com 的作答
importdatetimeprint('Timestamp: {%Y-%m-%d %H:%M:%S:%f}'.format(datetime.datetime.now()))