【python】python字符串占位符

python有三种字符串占位符方式,代码演示如下:

if __name__ == "__main__":
    name = "Lucy"
    age = 20
    # 方式一:占位符,%s表示只能接受string, %d代表只能接受数字
    print("name is %s and age is %d" % (name, age))
    # format的用法1,需要用{n}作占位符,占位符从0开始
    print("name is {0} and age is {1}".format(name, age))
    # format的用法2,需要用{alias(别名)}作占位符
    print("name is {_name} and age is {_age}".format(_name=name, _age=age))

输出:

name is Lucy and age is 20
name is Lucy and age is 20
name is Lucy and age is 20
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
发出的红包

打赏作者

郝少

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值