笨鸟编程-零基础入门Pyhton教程

 找回密码
 立即注册
查看: 3286|回复: 0

Python中%r和%s的区别

[复制链接]

新手上路

Rank: 1

积分
13
发表于 2022-3-13 19:27:56 | 显示全部楼层 |阅读模式

%r用rper()方法处理对象

%s用str()方法处理对象


函数str() 用于将值转化为适于人阅读的形式,而repr() 转化为供解释器读取的形式(如果没有等价的语法,则会发生SyntaxError 异常) 某对象没有适于人阅读的解释形式的话, str() 会返回与repr()等同的值。很多类型,诸如数值或链表、字典这样的结构,针对各函数都有着统一的解读方式。


有些情况下,两者处理的结果是一样的,比如说处理int型对象。

例一:

  1. print "I am %d years old." % 22
  2. print "I am %s years old." % 22
  3. print "I am %r years old." % 22
复制代码

返回结果:

  1. I am 22 years old.
  2. I am 22 years old.
  3. I am 22 years old.
复制代码

另外一些情况两者就不同了

例二:

  1. text = "I am %d years old." % 22
  2. print "I said: %s." % text
  3. print "I said: %r." % text
复制代码

返回结果:

  1. I said: I am 22 years old..
  2. I said: 'I am 22 years old.'.   #%r 给字符串加了单引号
复制代码

再看一种情况

例三:

  1. import datetime
  2. d = datetime.date.today()
  3. print "%s" % d
  4. print "%r" % d
复制代码

返回结果:

  1. 2017-08-16
  2. datetime.date(2017, 8, 16)
复制代码

可见,%r打印时能够重现它所代表的对象(rper() unambiguously recreate the object it represents)


回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

Archiver|手机版|笨鸟自学网 ( 粤ICP备20019910号 )

GMT+8, 2024-9-8 09:46 , Processed in 0.018250 second(s), 18 queries .

© 2001-2020

快速回复 返回顶部 返回列表