首頁>技術>

string 拼接

可以使用 + 實現兩個字串的拼接。

a = "Hello"b = "World"c = a + bprint(c)--- output ---PS E:\dream\markdown\python> & "C:/Program Files (x86)/Python/python.exe" e:/dream/markdown/python/app/app.pyHelloWorld

如果想調整一下格式,可以在 hellworld 之間加上空格,如下所示:

a = "Hello"b = "World"c = a + " " + bprint(c)--- output ---PS E:\dream\markdown\python> & "C:/Program Files (x86)/Python/python.exe" e:/dream/markdown/python/app/app.pyHello World
string 格式化

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

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

接下來看看 format,在字串中設定一個佔位符 {},佔位符的引數透過 format 傳入,如下所示:

age = 36txt = "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.pyMy name is John, and I am 36

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

quantity = 3itemno = 567price = 49.95myorder = "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.pyI want 3 pieces of item 567 for 49.95 dollars.

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

14
最新評論
  • BSA-TRITC(10mg/ml) TRITC-BSA 牛血清白蛋白改性標記羅丹明
  • Python 入門系列——9. string基礎和切片