在Python中,`%s` 是一个格式化字符串的占位符,用于将变量或表达式插入到字符串模板中。以下是`%s`的基本用法和一些高级用法:
基本用法
name = "Tom"age = 18print("My name is %s, I am %d years old." % (name, age))
输出:
My name is Tom, I am 18 years old.
高级用法
格式化多个数据值
name1 = "Tom"age1 = 18name2 = "Jerry"age2 = 20print("The first person is %s, %d years old. The second person is %s, %d years old." % (name1, age1, name2, age2))
输出:
The first person is Tom, 18 years old. The second person is Jerry, 20 years old.
字符串对齐

str2 = "abc"print("%3s" % str2) 输出:abcprint("%5s" % str2) 输出:abcprint("%15s" % str2) 输出:abc (左侧补全)print("%.3s" % str2) 输出:abcprint("%.6s" % str2) 输出:abc
带符号的字符串
a = "wry"b = "zjl"c = "xxx"print("a=%s, b=%s, c=%s" % (a, b, c))
输出:
a=wry, b=zjl, c=xxx
注意事项
`%s` 用于字符串的格式化。
当使用 `%s` 格式化字符串时,传递的参数会被自动转换为字符串。
如果需要格式化其他数据类型(如整数、浮点数等),应使用相应的格式化占位符,如 `%d`、`%.2f` 等。
希望这些信息能帮助你理解Python中`%s`的用法
