关于python:Python-入门系列-10-string-拼接-和-format-介绍

35次阅读

共计 1692 个字符,预计需要花费 5 分钟才能阅读完成。

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 <module>
    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.

译文链接:https://www.w3schools.com/pyt…

更多高质量干货:参见我的 GitHub: python

正文完
 0