4

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.

3
  • 1
    '\U0001F602' is evaluated during compile time and a string literal starting with \U has a special meaning for the compiler. '\{}'.format('U0001F602') is evaluated during runtime (and should be written with an escaped backslash as '\\{}'.format('U0001F602') anyway) Commented Oct 7, 2021 at 6:07
  • See Process escape sequences in a string in Python to solve the problem of turning the actual backslash, followed by capital U etc. into the emoji. As for the question that was actually asked, it's simple: \{ isn't a valid escape sequence, and Python handles that by treating the backslash literally. The now-linked duplicate is the best reference I could find for this problem - in more recent versions of Python, you will get such a warning message on this code. Commented Aug 7, 2022 at 4:50
  • (Warnings are disabled by default; you would need the -Wd flag for Python to see this.) Commented Aug 7, 2022 at 4:56

2 Answers 2

6

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.

Sign up to request clarification or add additional context in comments.

Comments

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

This is because you are giving {} as an argument to .format function and it only fills value inside the curly braces.

ANd it is printing a single \ not double \

7 Comments

Hi, you mentioned that i"t is printing a single \ not double \". Then why ('\{}'.format('U0001F602')) == ('\\{}'.format('U0001F602')) returns True ?
You have used '==' operator, that operator checks whether the LHS = RHS , and if yes it returns true, and both return the same thing
Understand it this way,
When you use \\ it thinks the first backslash is the begining of an excape sequence and \\ prints a \ while a single \ is treated as a string
Ok, I got it, Thank you
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.