欢迎大家来到IT世界,在知识的湖畔探索吧!
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
欢迎大家来到IT世界,在知识的湖畔探索吧!
如果想调整一下格式,可以在 hellworld 之间加上空格,如下所示:
欢迎大家来到IT世界,在知识的湖畔探索吧!
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 传入,如下所示:
欢迎大家来到IT世界,在知识的湖畔探索吧!
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/python/python_strings_slicing.asp
更多高质量干货:参见我的 GitHub: python
免责声明:本站所有文章内容,图片,视频等均是来源于用户投稿和互联网及文摘转载整编而成,不代表本站观点,不承担相关法律责任。其著作权各归其原作者或其出版社所有。如发现本站有涉嫌抄袭侵权/违法违规的内容,侵犯到您的权益,请在线联系站长,一经查实,本站将立刻删除。 本文来自网络,若有侵权,请联系删除,如若转载,请注明出处:https://itzsg.com/37171.html