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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With