How to use newline '\n' in f-string to format output in Python 3.6?

前端 未结 4 1110
自闭症患者
自闭症患者 2020-12-04 13:49

I would like to know how to format this case in a Pythonic way with f-strings:

names = [\'Adam\', \'Bob\', \'Cyril\']
text = f\"Winners are:\\n{\'\\n\'.join(         


        
4条回答
  •  萌比男神i
    2020-12-04 14:41

    You don't need f-strings or other formatters to print a list of strings with a separator. Just use the sep keyword argument to print():

    names = ['Adam', 'Bob', 'Cyril']
    print('Winners are:', *names, sep='\n')
    

    Output:

    Winners are:
    Adam
    Bob
    Cyril
    

    That said, using str.join()/str.format() here would arguably be simpler and more readable than any f-string workaround:

    print('\n'.join(['Winners are:', *names]))
    print('Winners are:\n{}'.format('\n'.join(names)))
    

提交回复
热议问题