什么时候在Python中使用%r而不是%s?
在学习Python困难的方法第21页,我看到这个代码示例:
x = "There are %d types of people." % 10 ... print "I said: %r." % x  为什么%r在这里用来代替%s ? 你什么时候使用%r ,什么时候使用%s ? 
  %s说明符使用str()转换对象, %r使用repr()转换它。 
 对于某些对象,如整数,它们会得到相同的结果,但repr()是特殊的(对于可能的types),它通常会返回一个有效的Python语法结果,可以用来明确地重新创build对象代表。 
以下是一个使用date的示例:
 >>> import datetime >>> d = datetime.date.today() >>> str(d) '2011-05-14' >>> repr(d) 'datetime.date(2011, 5, 14)' 
  repr()不能生成Python语法的types包括那些指向外部资源(如file ,不能保证在不同的上下文中重新创build。 
 使用%r进行debugging,因为它显示variables的“原始”数据,但是其他用于显示给用户。 
 这就是%r格式的工作原理。 它会按照您写入(或接近它)的方式进行打印。 这是debugging的“原始”格式。 这里\n用于显示给用户不起作用。  %r表示variables的原始数据。 
 months = "\nJan\nFeb\nMar\nApr\nMay\nJun\nJul\nAug" print "Here are the months: %r" % months 
输出:
 Here are the months: '\nJan\nFeb\nMar\nApr\nMay\nJun\nJul\nAug' 
从Python学习困难的方式检查这个例子 。
  %r用引号显示: 
这将是:
 I said: 'There are 10 types of people.'. 
 如果你使用%s那应该是: 
 I said: There are 10 types of people.. 
以上是本詹姆斯的回答:
 >>> import datetime >>> x = datetime.date.today() >>> print x 2013-01-11 >>> >>> >>> print "Today's date is %s ..." % x Today's date is 2013-01-11 ... >>> >>> print "Today's date is %r ..." % x Today's date is datetime.date(2013, 1, 11) ... >>> 
当我运行这个时,它帮助我看到%r的有用性。