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

Viewed 106

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!

3 Answers

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.

For the reason why you saw that behavior you can see @Alfe's answer.

For solution there are two encodings that can help you if you don't want to use eval or exec which is do not recommended. 'raw-unicode-escape' and 'unicode-escape'

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

print(a.encode('raw-unicode-escape').decode('unicode-escape'))

\n is the escape code for a new line. As soon as it reads \n it breaks anything after into a new line.

When you use it as string = f'\{variable}' you're passing formatted text so the slash is being read as part of the string.

To achieve what you're probably asking you want to use string = f'\n{variable}'

See these examples of using escape codes

Related