0

I'm using python v3.8 with jupyter lab notebook, and I'm having problems with using f-string instead of regular print in a loop. When I write in one cell

a=2
f" a={a}"\
f" a={a+1}+1 "

the output is ' a=2 a=3+1 ' (and without that 'back slash' character it would be just ' a=3+1 ', so I guess second f-string overwrites the first one here), but in the case of the loop like

for i in range(11):
    f"{i}"

there is no output at all, while I want numbers to be printed like this

1
2
...
10

What am I doing wrong here?

lugger1
  • 1,843
  • 3
  • 22
  • 31

2 Answers2

1

You need to add a print statement around the formatted string:

for i in range(11):
    print(f"{i}")
DapperDuck
  • 2,728
  • 1
  • 9
  • 21
  • Right! I somehow decided that f-string can be used instead of print(), not as another formatting tool but as a substitution of print()... It was a long week :) – lugger1 Feb 06 '21 at 00:55
1

It has nothing to do with f-strings.

Without print functions, Jupyter notebooks only display the result of the last line in the cell:

a cell with 3 lines without print and a cell with 3 lines with print

When you use a backslash, it continues the line and Python considers it one longer line. Multiple quoted strings are treated as one longer string:

3 quoted strings on one line, 3 quoted string on separate linse, 3 quoted strings with trailing backslashes on separate lines

Mark Tolonen
  • 166,664
  • 26
  • 169
  • 251
  • Right! I just forgot that in jupyter to get output I don't necessary need to call print() directly, that's why f".." was producing output by itself, but not in loop. – lugger1 Feb 06 '21 at 00:58