《笨办法学python》习题9中%r与%s的见解

formatter = "%r %r %r %r"
#formatter = "%s %s %s %s"

print(formatter % (1, 2, 3, 4) )
print(formatter % ("one", "two", "three", "four"))
print(formatter % (True, False, False, True) )
print(formatter % (formatter, formatter, formatter, formatter))
print( formatter % (
      "I had this thing.",
      "That you could type up right.",
      "But it didn't sing.",
      "So I said goodnight."
                    )
       )

面对这个程序,大量的%让我感到头疼,我并不清楚%r与%s的区别与使用方法。在经过一定的查找后我找到了最合适的解释:

这是Python中的字符串格式化。

在这个例子中,%r是一个占位符,用于表示将要被替换的值。

在第一个print语句中,%r被替换为1、2、3和4。在第二个print语句中,%r被替换为字符串"one"、“two”、“three"和"four”。

在第三个print语句中,%r被替换为True、False、False和True。

在第四个print语句中,%r被替换为formatter本身四次。

在最后一个print语句中,formatter被替换为"I had this thing.", “That you could type up right.”, “But it didn’t sing.”, and “So I said goodnight.”。

请注意,这里使用的是%r占位符,而不是%s占位符。%r占位符用于调试目的,因为它会显示原始数据,而不是字符串的解释版本。如果使用%s占位符,则会显示字符串的解释版本。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值