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

前端 未结 4 1126
自闭症患者
自闭症患者 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条回答
  •  无人及你
    2020-12-04 14:32

    You can't use backslashes in f-strings as others have said, but you could step around this using os.linesep (although note this won't be \n on all platforms, and is not recommended unless reading/writing binary files; see Rick's comments):

    >>> import os
    >>> names = ['Adam', 'Bob', 'Cyril']
    >>> print(f"Winners are:\n{os.linesep.join(names)}")
    Winners are:
    Adam
    Bob
    Cyril 
    

    Or perhaps in a less readable way, but guaranteed to be \n, with chr():

    >>> print(f"Winners are:\n{chr(10).join(names)}")
    Winners are:
    Adam
    Bob
    Cyril
    

提交回复
热议问题