python中print的用法是什么

小億
87
2023-11-29 09:08:54

在Python中,print()函數(shù)用于將指定的數(shù)據(jù)打印到控制臺(tái)或輸出文件中。

print()函數(shù)的語(yǔ)法如下:

print(value1, value2, ..., sep=' ', end='\n', file=sys.stdout, flush=False)

參數(shù)說(shuō)明:

  • value1, value2, ...:要打印的值。
  • sep:可選參數(shù),用于指定不同值之間的分隔符,默認(rèn)為一個(gè)空格。
  • end:可選參數(shù),用于指定打印結(jié)束后的字符,默認(rèn)為換行符\n。
  • file:可選參數(shù),用于指定輸出的文件對(duì)象,默認(rèn)為標(biāo)準(zhǔn)輸出(控制臺(tái))。
  • flush:可選參數(shù),用于指定是否立即刷新文件,默認(rèn)為False。

示例:

print("Hello, World!")  # 打印字符串
print(10)  # 打印整數(shù)
print(3.14)  # 打印浮點(diǎn)數(shù)

name = "Alice"
age = 25
print("Name:", name, "Age:", age, sep='|')  # 指定分隔符

print("Hello", end='')  # 不換行打印
print("World!")

file = open("output.txt", "w")
print("Hello, File!", file=file)  # 輸出到文件
file.close()

輸出結(jié)果:

Hello, World!
10
3.14
Name:|Alice|Age:|25
HelloWorld!

注意:print()函數(shù)是Python 3.x中的函數(shù),而在Python 2.x中是作為語(yǔ)句使用的。在Python 2.x中,可以直接使用print語(yǔ)句來(lái)打印內(nèi)容,例如print "Hello, World!"。

0