Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why print returns \\, not a escape character \ in Python

The below code prints the emoji like, this 😂 :

print('\U0001F602')
print('{}'.format('\U0001F602'))

However, If I use \ like the below, it prints \U0001F602

print('\{}'.format('U0001F602'))

Why the print('\{}'.format()) retunrs \\, not a escape character, which is \?

I have been checking this and searched in Google, but couldn't find the proper answer.

like image 840
Chanhee Avatar asked Mar 02 '23 10:03

Chanhee


1 Answers

Referring to String and Bytes literals, when python sees a backslash in a string literal while compiling the program, it looks to the next character to see how the following characters are to be escaped. In the first case the following character is U so python knows its a unicode escape. In the final case, it sees {, realizes there is no escape, and just emits the backslash and that { character.

In print('\{}'.format('U0001F602')) there are two different string literals '\{}' and 'U0001F602'. That the first string will be parsed at runtime with .format doesn't make the result a string literal at all - its a composite value.

like image 97
tdelaney Avatar answered Mar 12 '23 11:03

tdelaney