Python 字符串占位符与.format格式化的用法

直接上代码,一看就能懂:

my_name = 'Richard'
age = 22
salary = int(input('please input your salary:'))

#method 1 占位符,%s表示只能接受string, %d代表只能接受数字,所以上边salary接受的input输入,需要强转为int类型
res1 = 'res1: My name is %s ,I\'m %d years old, my salary is %d'%(my_name,age,salary)
print(res1)

#method 2 .format的用法1,需要用{n}作占位符,占位符从0开始
res2 = 'res2: My name is {0} ,I\'m {1} years old, my salary is {2}'.format(my_name,age,salary)
print(res2)

#method 3 .format的用法2,需要用{alias}作占位符
res3 = 'res3: My name is {_name} ,I\'m {_age} years old, my salary is {_salary}'.format(_name=my_name,_age=age,_salary=salary)
print(res3)

运行结果:

please input your salary:22222
res1: My name is Richard ,I'm 22 years old, my salary is 22222
res2: My name is Richard ,I'm 22 years old, my salary is 22222
res3: My name is Richard ,I'm 22 years old, my salary is 22222

 

转载于:https://www.cnblogs.com/Richard-Liang/p/10743831.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Python 中,字符串是一种用于格式化字符串的特殊语法。以下是 Python 中常用的字符串: - `%s`:用于字符串格式化,表示用字符串替换。 - `%d`:用于整数格式化,表示用整数替换。 - `%f`:用于浮点数格式化,表示用浮点数替换。 - `%x`:用于十六进制格式化,表示用十六进制数替换。 例如,以下代码将使用字符串格式化一个字符串: ```python name = 'John' age = 25 height = 1.75 # 使用字符串格式化字符串 msg = "My name is %s, I'm %d years old, and I'm %.2f meters tall." % (name, age, height) print(msg) ``` 输出结果为: ``` My name is John, I'm 25 years old, and I'm 1.75 meters tall. ``` 除了使用 `%` 运算外,还可以使用 `format()` 方法进行字符串格式化。例如: ```python name = 'John' age = 25 height = 1.75 # 使用 format() 方法格式化字符串 msg = "My name is {}, I'm {} years old, and I'm {:.2f} meters tall.".format(name, age, height) print(msg) ``` 输出结果与上例相同: ``` My name is John, I'm 25 years old, and I'm 1.75 meters tall. ``` 需要注意的是,Python 3.6 及以后版本还引入了 f-string 语法,可以更方便地进行字符串格式化。例如: ```python name = 'John' age = 25 height = 1.75 # 使用 f-string 格式化字符串 msg = f"My name is {name}, I'm {age} years old, and I'm {height:.2f} meters tall." print(msg) ``` 输出结果也与上例相同: ``` My name is John, I'm 25 years old, and I'm 1.75 meters tall. ```

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值