代码之家  ›  专栏  ›  技术社区  ›  nilsinelabore

字符串格式为空字符串导致打印中有多余空间

  •  0
  • nilsinelabore  · 技术社区  · 1 年前

    我想字符串格式的句子如下:

    integer = 1
    if integer != 1:
        n_val, book = integer, 'books'
    else:
        n_val, book ='', 'book'
    
    print(f'Fetch the top {n_val} children {book}.')
    

    我希望看到:

    Fetch the top 3 children books.
    

    Fetch the top children book.
    

    如果integer不为1,则它有效,但是,当 integer =1 ,字符串格式在integer的位置给了我一个额外的空间,如下所示:

    Fetch the top  children book.
    

    整数=1 ?

    1 回复  |  直到 1 年前
        1
  •  1
  •   Tim Roberts    1 年前

    使空间成为变量的一部分。

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