Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does \n work only in f string when inside print?

I'm working on a school assigment for python/pandas and wanted to try out f strings as seemed very handy way of formatting.

After reading documentation, I realised that I couldn't use \n to format the output. For this code:

    f"Shape of dataset:\n {df.shape} (rows, columns)\n"

I get this output:

Out[38]: 'Shape of dataset:\n (270792, 11) (rows, columns)\n'

Which is exactly what I expected after reading the docs.

But then, when I surround it by a print(), as such:

print(f"Shape of dataset:\n {df.shape} (rows, columns)\n")

I get it looking the way I wanted:

Shape of dataset:
 (270792, 11) (rows, columns)

I know I could just use regular formatting as well, but I'm curious as to why this is. Is it that the f string component is ignored because of the print?

like image 668
Laura Prado Avatar asked Dec 11 '22 03:12

Laura Prado


2 Answers

This isn't specific to f-strings. This is the result in QPython's REPL on my phone:

>> "\nhello\n" 
'\nhello\n'

If you enter a String into a REPL, escape characters (like "\n") are left as-is. They are only "expressed" when explicitly printed out. Even though the P in REPL stands for "print", the REPL evidently uses a different mechanism for printing, or manually escapes the characters for you before printing to preserve them.

This can be useful when examining strings, since slightly "invisible" characters like newlines and tabs can be difficult to spot in printed output.

like image 171
Carcigenicate Avatar answered Dec 21 '22 16:12

Carcigenicate


The following are some examples that illustrate the point that when you enter a string into a Python/IPython Repl, the repr form of the string is shown. It does not matter which string formatter you use(f-strings or .format()). However, when you print it, it gets formatted and escapes characters like newlines, tabs etc.

In [18]: f"a\nb\n"
Out[18]: 'a\nb\n'

In [19]: print(f"a\nb\n")
a
b


In [20]: f"a\tb\tc"
Out[20]: 'a\tb\tc'

In [21]: print(f"a\tb\tc")
a       b       c

In [22]: a = 1

In [23]: b=2

In [24]: "a={}\nb={}".format(a,b)
Out[24]: 'a=1\nb=2'

In [25]: print("a={}\nb={}".format(a,b))
a=1
b=2

In [26]: "a={}\tb={}".format(a,b)
Out[26]: 'a=1\tb=2'

In [27]: print("a={}\tb={}".format(a,b))
a=1     b=2

Python provides a repr() function that shows the printable representation of the object. All statements without the print above use this internally in the Python/IPython console. There is also the str() function that formats the object. Internally, when you print the string, str() is applied first that formats the string.

In [29]: print(repr(f"a\tb\tc"))
'a\tb\tc'

In [30]: print(str(f"a\tb\tc"))
a       b       c
like image 22
amanb Avatar answered Dec 21 '22 18:12

amanb