string 拼接
可以使用 +
实现两个字符串的拼接。
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 之间加上空格,如下所示:
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 ,先看一下之前的例子。
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
txt = "My name is John, I am " + age
TypeError: can only concatenate str (not "int") to str
接下来看看 format,在字符串中设置一个占位符 {}
,占位符的参数通过 format 传入,如下所示:
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
有些朋友可能就要问了,既然支持一个 占位符,那能不能支持多个占位符呢? 当然可以啦,如下所示:
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# 中的数字型占位符形式,实现精准指向性占位。
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.
更多高质量干货:参见我的 GitHub: github.com/ctripxchuang/python