简体   繁体   English

Python转义序列和字符串操作

[英]Python Escape Sequence and String Manipulation

I have the following two vars: 我有以下两个变量:

a = chr(92) + 'x11'
b = '\x11'
print 'a is: ' + a
print 'b is: ' + b

The result of these print statemtents: 这些打印状态提示的结果:

a is: \x11
b is: <|        # Here I am just showing a representation of the symbol that is printed for b

How can I make it so that variable a prints the same thing as var b using the chr(92) call? 我该如何使变量a使用chr(92)调用输出与var b相同的内容? Thank you in advance. 先感谢您。

The other answers are showing you how to make b give you what you get in a . 其他答案您展示如何让b给你什么你得到a If you want a to give you what you get in b (which is what you're asking, if I read you correctly), you need to decode the escape sequence: 如果您想让a给出您从b得到的结果(如果我没看错的话,这就是您的要求),则需要对转义序列进行解码:

>>> a
u'\\x11'
>>> a.decode('string-escape')
'\x11'

You can also use unicode-escape instead of string-escape if you want a unicode string as the result. 如果您想要unicode字符串作为结果,也可以使用unicode-escape而不是string-escape

Check out the documentation for string literals . 请查阅文档中有关字符串文字的信息

Backslash is an escape character in Python strings, so to include a literal backslash in your string you need to escape them by using two consecutive backslashes. 反斜杠是Python字符串中的转义字符,因此要在字符串中包含文字反斜杠,您需要使用两个连续的反斜杠对它们进行转义。 Alternatively, you can suppress the escaping behavior of backslashes by using a raw string literal, which is done by prefixing the string with r . 另外,您可以通过使用原始字符串文字来抑制反斜杠的转义行为,这可以通过在字符串前面加上r For example: 例如:

  • Escaping the backslash: 转义反斜杠:

     b = '\\\\x11' 
  • Using a raw string literal: 使用原始字符串文字:

     b = r'\\x11' 

If I am misinterpreting your question and b should be '\\x11' or equivalently chr(17) , but you just want it to display in the escaped format, you can use repr() for that: 如果我误解了您的问题,并且b应该是'\\x11'或等效的chr(17) ,但是您只希望它以转义格式显示,则可以使用repr()

>>> b = '\x11'
>>> print 'b is: ' + repr(b)
b is: '\x11'

If you don't want the quotes, use the string_escape encoding : 如果您不想使用引号,请使用string_escape编码

>>> print 'b is: ' + b.encode('string_escape')
b is: \x11

Or to get a to be the same as b , you can use a.decode('string_escape') . 或者得到a是一样的b ,你可以使用a.decode('string_escape')

\\x11 appears to be the hex value for a ^Q control character in ASCII: \\x11似乎是ASCII中的^Q控制字符的十六进制值:

\021  17  DC1  \x11  ^Q    (Device control 1) (XON) (Default UNIX    START char.)

You need to escape the \\ to get the literal \\x11 您需要转义\\以获得文字\\x11

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

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