Why doesn’t adding a backslash in front of an f-string make it an escape sequence

I wanted to know why this:

a = 'nabc'

print(a)

gives:

abc

and why does this:

a = 'n abc'
a = f'{a}'

print(a)

gives:

n abc

instead of this:

abc

and how can I make this:

a = 'n abc'
a = f'{a}'

print(a)

gives:

abc

instead of:

n abc

Please help!

Answer

You can’t. If at some point in your program your statement is

a = f'{a}'

print(a)

then no value of a can make this print a newline first.

The reason is that the line a= f'{a}' prepends a backslash to the contents of the string a. To prepend a newline you would need to write this: a = f'n{a}'.

You see, the is a character and the n is a character as well. It’s one character, not two. The n is a notation in source code to name one single character, namely the newline character. So adding a to anything will not create a newline.

Your problem sounds very much like an A/B problem in which you ask for A because you want to achieve B and think that A is the correct way. It probably isn’t in your case. I propose to tell us why you want to do this, then probably we can give you a much more helpful advice than my initial “You can’t”.

EDIT: As it turns out, you have "U00000D05" in a variable and want to create (and print) the unicode character of that number:

print(chr(int(s[1:], 16)))

The int(x, 16) converts a string of hex digits into an int. chr() then converts the int to a unicode character.

Btw, your original approach was to use the Python parser to create the character. This also is possible but not recommended (the way given above is the straight forward one, it’s safe and fast). To use the parser nevertheless use this:

s = "U00000D05"
print(eval('"\' + s + '"'))

Here you build a string starting and ending with a doublequote a which contains U00000D02 between them (so the string’s contents is "U00000D02"), and this is given to eval() which calls the Python parser for a value.

But as I said, this is not the recommended way to do it. With a malicious value in s this even bears a security risk. Don’t use eval() if you don’t know exactly what you are doing.