简体   繁体   English

以八进制打印文字字符串python

[英]Printing a literal string python in octal

Hi I am having trouble trying to print a literal string in a proper format. 嗨我在尝试以适当的格式打印文字字符串时遇到问题。 For starters i have an object with a string parameter which is used for metadata such that it looks like: 对于初学者,我有一个带有字符串参数的对象,该参数用于元数据,如下所示:

obj {
    metadata: <str>
}

The object is being returned as a protocol response and we have the object to use as such. 该对象作为协议响应返回,我们有对象可以这样使用。

print obj gives: print obj给出:

    metadata: "\n)\n\022foobar"

When I print the obj.metadata python treats the value as a string and converts the escapes to linebreaks and the corresponding ascii values as expected. 当我打印obj.metadata时,python将值视为字符串,并将转义符转换为换行符和相应的ascii值。

When i tried print repr(obj.metadata) 当我尝试打印repr(obj.metadata)时

"\n)\n\x12foobar"

Unfortunately python prints the literal but converts the escaped characters from octal to hex. 不幸的是,python打印文字但将转义的字符从八进制转换为十六进制。 Is there a way i can print the python literal with the escaped characters in octal or convert the string such that I can have the values printed as it is in the object? 有没有办法我可以用八进制中的转义字符打印python文字或转换字符串,以便我可以打印在对象中的值?

Thanks for the help 谢谢您的帮助

The extremely bad solution I have so far is 到目前为止我的解决方案非常糟糕

print str(obj).rstrip('\"').lstrip('metadata: \"')

to get the correct answer, but i am assuming there must be a smarter way 得到正确的答案,但我认为必须有一个更聪明的方法

TLDR: TLDR:

x = "\n)\n\022foobar"
print x

)
foobar

print repr(x)
'\n)\n\x12foobar'

how do i get x to print the way it was assigned 如何让x打印它的分配方式

Please try this: 请试试这个:

print('\\\n)\\\n\\\022foobar') 

or 要么

print(r'\n)\n\022foobar')

The escape character '\\' interprets the character following it differently, for example \\n is used for new line. 转义字符'\\'以不同的方式解释跟随它的字符,例如\\n用于换行。

The double escape character '\\\\' or letter 'r' nullifies the interpretation of the escape character. 双转义字符'\\\\'或字母'r'使转义字符的解释无效。 This is similar in C language. 这与C语言类似。

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

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