Python 入門系列 —— 10. string 拼接 和 format 介紹

string 拼接

能夠使用 + 實現兩個字符串的拼接。python

a = "Hello"
b = "World"
c = a + b
print(c)

--- output ---

PS E:\dream\markdown\python> & "C:/Program Files (x86)/Python/python.exe" e:/dream/markdown/python/app/app.py
HelloWorld

若是想調整一下格式,能夠在 hellworld 之間加上空格,以下所示:git

a = "Hello"
b = "World"
c = a + " " + b
print(c)

--- output ---

PS E:\dream\markdown\python> & "C:/Program Files (x86)/Python/python.exe" e:/dream/markdown/python/app/app.py
Hello World

string 格式化

還記得在前面的文章中提到,將 string 和 int 進行拼接是行不通的,這時候的解決方案就是用 format ,先看一下以前的例子。github

age = 36
txt = "My name is John, I am " + age
print(txt)

--- output ---

PS E:\dream\markdown\python> & "C:/Program Files (x86)/Python/python.exe" e:/dream/markdown/python/app/app.py
Traceback (most recent call last):
  File "e:/dream/markdown/python/app/app.py", line 2, in <module>
    txt = "My name is John, I am " + age
TypeError: can only concatenate str (not "int") to str

接下來看看 format,在字符串中設置一個佔位符 {},佔位符的參數經過 format 傳入,以下所示:markdown

age = 36
txt = "My name is John, and I am {}"
print(txt.format(age))

PS E:\dream\markdown\python> & "C:/Program Files (x86)/Python/python.exe" e:/dream/markdown/python/app/app.py
My name is John, and I am 36

有些朋友可能就要問了,既然支持一個 佔位符,那能不能支持多個佔位符呢? 固然能夠啦,以下所示:app

quantity = 3
itemno = 567
price = 49.95
myorder = "I want {} pieces of item {} for {} dollars."
print(myorder.format(quantity, itemno, price))

--- output ---

PS E:\dream\markdown\python> & "C:/Program Files (x86)/Python/python.exe" e:/dream/markdown/python/app/app.py
I want 3 pieces of item 567 for 49.95 dollars.

除了這種通用的佔位符,還能夠使用相似 C# 中的數字型佔位符形式,實現精準指向性佔位。code

quantity = 3
itemno = 567
price = 49.95
myorder = "I want to pay {2} dollars for {0} pieces of item {1}."
print(myorder.format(quantity, itemno, price))

--- output ---

PS E:\dream\markdown\python> & "C:/Program Files (x86)/Python/python.exe" e:/dream/markdown/python/app/app.py
I want to pay 49.95 dollars for 3 pieces of item 567.
譯文連接: https://www.w3schools.com/pyt...

更多高質量乾貨:參見個人 GitHub: pythonorm

相關文章
相關標籤/搜索