Print:打印標準輸出的函數
格式:print()
print()函數有三個參數
讓客戶滿意是我們工作的目標,不斷超越客戶的期望值來自于我們對這個行業的熱愛。我們立志把好的技術通過有效、簡單的方式提供給客戶,將通過不懈努力成為客戶在信息化領域值得信任、有價值的長期合作伙伴,公司提供的服務項目有:域名申請、虛擬主機、營銷軟件、網站建設、云巖網站維護、網站推廣。
函數參數使用舉例:
>>>num1=2 >>>str1='words' >>>print(num1,str1) 2 words
默認2與words之間有一個空格,輸出完成之后有一個回車
使用了@作為分割符>>>print(num1,str1,sep='@') 2@words
使用&作為結尾
>>>print(num1,str1,sep='@',end='&') 2@words&
其實print函數還有一個參數file,通常print函數都是stdout方式輸出,但是如果需要將輸出結果重定向到一個文件可以使用file參數
f=open("d:\\new.txt","w") for i in range(6): print("new line",file=f)
此時在d盤更目錄下會自動創建一個new.txt文件,并打印6行new line在其中。
【Case1】
直接輸出打印內容
>>>print("This is a new word.") This is a new word.
如果內容過長,可以使用\作為換行符
>>>print("This is a new \ word") This is a new word
【Case2】
使用變量打印內容
>>> a="This is a new word." >>> print(a) This is a new word.
【Case3】
使用三引號作為格式打印
>>>str=""" This is a new word . """ >>>print(str) This is a new word .
【Case4】
除了使用三引號作為格式化輸出,還有兩種格式化輸出的方式%和.format
使用%占位符格式化打印
主要使用的占位符有:
%s 字符串
%r 字符串
%d 十進制整數
%i 十進制整數
%f 浮點數>>>str1='world' >>>print('hello %s' %'world') hello world
>>>print('hello %s' %str1) hello world
>>>str='abc' >>>print("%s" %str) abc >>> print("%s" %str.title()) Abc
>>>print('hello %r' %str1) hello 'world'
>>>num1=300 >>>print ('the number is','%d' %num1) the number is 300
>>>print ('the number is','%i' %num1) the number is 300
>>> num2=30 >>> name='John' >>> print('He is %s, he is %d years old.' %(name,num2)) He is John, he is 30 years old.
其它占位符:
%c 單個字符
%b 二進制整數
%o 八進制整數
%x 十六進制整數
%e 指數 (基底寫為e)
%E 指數 (基底寫為E)
%F 浮點數,與上相同
%g 指數(e)或浮點數 (根據顯示長度)
%G 指數(E)或浮點數 (根據顯示長度使用format()方法格式化打印
>>> str=''' Username={uname} Id={id} Phone={tel} '''.format(uname='Jone',id='123',tel='138***') >>> print(str) Username=Jone Id=123 Phone=138***
>>> str2="{0}".format("abc") >>> print(str2) abc
>>> str=''' username={0} Id={1} Phone={2} '''.format('Jone','123','138***') >>> print(str) username=Jone Id=123 Phone=138***
【Case5】
轉義字符
常用轉義字符:
/t 輸出一個橫向指標符
/n 輸出一個換行符
/v 輸出一個縱向制表符
/f 輸出一個換頁
/r 輸出一個回車