python中format和int_Python 入门系列 —— 10. string 拼接 和 format 介绍

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: python

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值