Search code examples
pythonstring-formatting

String format empty string caused extra space in print


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?


Solution

  • 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}.')