Why print returns \, not a escape character in Python
Question:
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.
Answers:
>>> 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
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.
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.
>>> 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
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.