10.格式化輸出

什麼是格式化輸出?
我們寫程序時,可能會用到一段字符串多次,比如:我的名字是xxx,年齡xxx,
每次寫的時候’我的名字’和’年齡’需要重複寫。我們可以寫一個特定的字符串,使用時只需填入姓名和年齡即可。
通俗來說就是:改變固定字符串的某些字符。
下面介紹三種方法:

1.佔位符

ps:佔位符分好多種,我們只需記%s足夠使用
1.根據位置

words = "my name is %s,age is %s" %("alex",18)
print(words)							結果爲:my name is alex,age is 18

2.根據關鍵字

words = "my name is %(name)s,age is %(age)s" %{"name":"alex","age":18}
print(words)							結果爲:my name is alex,age is 18

2.string.format()

1.根據位置

words = "my name is {},age is {}".format("alex",123)
print(words)							結果爲:my name is alex,age is 123

2.根據索引

words = "my name is {0},age is {1},name is {1},age is {0}".format("alex",123)
print(words)							結果爲:my name is alex,age is 123,name is 123,age is alex		

3.根據關鍵字

words = "my name is {name},age is {age}".format(name="alex",age=123)
print(words)							結果爲:my name is alex,age is 123

3.f-string

1.輸入內容可以是字符串

name = "alex"
age = 456
words = f'name is {name},age is {age}'
print(words)							結果爲:name is alex,age is 456

2.輸入的內容也可以是表達式

def func():
	return "hhhh"
words = f'{func()}'
print(words)							結果爲:hhhh

三種方式的比較:

  1. 佔位符是最早推出的,但速度比較慢
  2. f-string是python3.5以後纔有的,速度比較快
  3. format的話則是中規中矩,我個人喜歡用format
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章