简体   繁体   English

%r在格式字符串中做什么?

[英]What does %r do in a format string?

I was doing a code to accept some file path as command line argument and then wanted to see what %r does... I tried few things, please go through the following code and let me know how exactly does the %r specifier works and why there is '\\' before p. 我正在做一个代码来接受某些文件路径作为命令行参数,然后想看看%r的作用...我尝试了几件事,请仔细阅读以下代码,让我知道%r说明符的工作原理以及为什么在页前有'\\'。

string1 = "C:\raint\new.txt"

string2 = "%r"%string1
string3 = string2[1:-1]

print "Input String: ",string2           
print "Raw String: ",string3  

string1 = "C:\raint\pint.txt"

string2 = "%r"%string1
string3 = string2[1:-1]

print "Input String: ",string2           
print "Raw String: ",string3            

Output:

Input String: 'C:\raint\new.txt'
Raw String: C:\raint\new.txt
Input String: 'C:\raint\\pint.txt'
Raw String: C:\raint\\pint.txt

It is string formatter just as there are other formatters like %s for string, %d for integer. 正如其他格式化程序一样,它是字符串格式化程序,例如%s表示字符串,%d表示整数。 Essentially when you encounter a formatter like %s or %r, a specific method is called on that object. 本质上,当您遇到%s或%r之类的格式化程序时,将在该对象上调用特定方法。 In case of %s, it str() method and in case of %r it is repr() method. 如果是%s,则为str()方法;如果为%r,则为repr()方法。 Some good reference resources are: 一些好的参考资源是:

  1. Diff between str and repr str和repr之间的差异
  2. Python3 doc Python3文件
  3. Related stuff for formatters 格式化程序的相关资料

%r does the conversion using repr() function. %r使用repr()函数进行转换。 It returns exact representation of object. 它返回对象的精确表示。 Using repr() most of the data types have the similar output, but we can find the difference below. 使用repr()大多数数据类型具有相似的输出,但是我们可以在下面找到区别。

>>> import datetime
>>> date = datetime.date.today()
>>> date
datetime.date(2019, 7, 3)
>>> str(date)
'2019-07-03'
>>> repr(date)
'datetime.date(2019, 7, 3)'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM