Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is '\x' invalid in Python?

I was experimenting with '\' characters, using '\a\b\c...' just to enumerate for myself which characters Python interprets as control characters, and to what. Here's what I found:

\a - BELL \b - BACKSPACE \f - FORMFEED \n - LINEFEED \r - RETURN \t - TAB \v - VERTICAL TAB 

Most of the other characters I tried, '\g', '\s', etc. just evaluate to the 2-character string of a backslash and the given character. I understand this is intentional, and makes sense to me.

But '\x' is a problem. When my script reaches this source line:

val = "\x" 

I get:

ValueError: invalid \x escape 

What is so special about '\x'? Why is it treated differently from the other non-escaped characters?

like image 633
PaulMcG Avatar asked Apr 24 '10 13:04

PaulMcG


People also ask

Why does Python keep saying invalid syntax?

Syntax errors are produced by Python when it is translating the source code into byte code. They usually indicate that there is something wrong with the syntax of the program. Example: Omitting the colon at the end of a def statement yields the somewhat redundant message SyntaxError: invalid syntax.

What does '\ t mean in Python?

In Python strings, the backslash "\" is a special character, also called the "escape" character. It is used in representing certain whitespace characters: "\t" is a tab, "\n" is a newline, and "\r" is a carriage return.

Why does Python say += is invalid?

x += 1 is an augmented assignment statement in Python. You cannot use statements inside the print statement , that is why you get the syntax error. You can only use Expressions there.

What does Pyflakes invalid syntax mean?

if variable > 10 print(variable + str(" > 10")) # there is no ":" next to the 10 in the 1st line, that will activate an error which is "SyntaxError : invalid syntax" # [pyflakes] significate something is missing in your code. if variable > 10. 2. print(variable + str(" > 10"))


2 Answers

There is a table listing all the escape codes and their meanings in the documentation.

 Escape Sequence    Meaning                        Notes \xhh               Character with hex value hh    (4,5) 

Notes:

4. Unlike in Standard C, exactly two hex digits are required.
5. In a string literal, hexadecimal and octal escapes denote the byte with the given value; it is not necessary that the byte encodes a character in the source character set. In a Unicode literal, these escapes denote a Unicode character with the given value.

like image 64
Mark Byers Avatar answered Oct 06 '22 17:10

Mark Byers


\xhh is used to represent hex escape characters.

like image 26
unutbu Avatar answered Oct 06 '22 18:10

unutbu