String format empty string caused extra space in print

Question:

I want to string format a sentence as below:

integer = 1
if integer != 1:
    n_val, book = integer, 'books'
else:
    n_val, book ='', 'book'

print(f'Fetch the top {n_val} children {book}.')

and I expected to see:

Fetch the top 3 children books.

or

Fetch the top children book.

It works if integer is not 1, however, when integer =1, the string format gives me an additional space in the place of integer as shown below:

Fetch the top  children book.

How do I get rid of the space when integer =1?

Asked By: nilsinelabore

||

Answers:

Make the space part of the variable.

integer = 1
if integer != 1:
    n_val, book = ' '+str(integer), 'books'
else:
    n_val, book ='', 'book'

print(f'Fetch the top{n_val} children {book}.')
Answered By: Tim Roberts
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.