1. 程式人生 > >Python基礎:十二、格式化輸出print() , input()

Python基礎:十二、格式化輸出print() , input()

占位符 一個空格 自動添加 con code nbsp python基礎 分號 int

利用 print() 進行格式化輸出

在print()的結尾,python解釋器會自動添加換行符,可以通過在print中加上end="內容"將換行符替換為end後的內容(內容可以為空)

print("你好",end="嗎?")
print("今天天氣不錯")
#輸出結果為:你好嗎?今天天氣不錯

轉義字符:\

換行:\n

print(a,b,c)
#輸出結果會為:a b c  中間有空格隔開
#print()對空格敏感
print(this is an nice day,the weather is sunny,and the temperature is 15 centigrade
)

格式化輸出

第一種寫法:加法太多,會導致內存耗費太多(每次加法其實都會產生一個新的字符串)

print("this is a" + condition + "day , theweather is" + weather + "and the temperature is" + temperature 

第二種寫法:占位符寫法

%s 字符串的占位符,但也可以放置任何內容

在末尾放上%(),括號內的內容是需要放的字符串或數字,按安放順序排列,%後的小括號可寫可不寫,%前最好加一個空格

print("this is a %s day , the weather is %s , and the temperature is %s 
" %( condition , weather , temperature))

%d數字的占位符

age=input("How old are you?")
age=int(age)
print("His age is %d" %(age))

如果字符串中有了占位符,那麽後面的所有%都是占位,需要轉義

但如果沒有占位符,百分號還是百分號

condition="cloudy"
print("%s is just 20% in a year" %(condition))   #錯誤寫法,因為在20%前已經有了占位符,此處的%需要轉義
print("
cloudy is just 20% in a year") #此時因為沒有占位符,百分號是正常的,不需要轉義 print("%s is just 20 %% in a year " %(condition)) #在需要轉義的%號前再加一個%,即寫為20%%可完成轉義

利用 input() 格式化輸出

#例:詢問天氣
condition=input("How‘s today")
weather=input("what‘s the weather today?")
temperature=input("what‘s the temperature today?(incentigrade)")

Python基礎:十二、格式化輸出print() , input()