python的s%和d%
Python中的字符串格式化有两种方式:s%和d%。
s%用于将一个或多个变量插入到一个用%s表示的字符串中。
age = 25
name = 'Amy'
print('My name is %s, and I am %d years old.' % (name, age))
# 输出:My name is Amy, and I am 25 years old.
d%用于将一个数字插入到一个用%d表示的字符串中。
num = 18
print('I have %d cats.' % num)
# 输出:I have 18 cats.
需要注意的是,如果要插入多个变量,需要用括号把它们括起来。
另外,格式化字符串还支持一些特殊符号,如\n表示换行,\t表示制表符等。
除以上两种方法,Python 3.0以后还提供了一种新的字符串格式化方式,即格式化字符串字面值(f-string)。
age = 25
name = 'Amy'
print(f'My name is {name}, and I am {age} years old.')
# 输出:My name is Amy, and I am 25 years old.
使用f-string,我们可以直接在字符串中插入变量,而不需要使用%s或%d。
文章来源:丸子建站
文章标题:python的s%和d%
https://www.wanzijz.com/view/70270.html