我有一个格式化的print语句,我想在三个单独的行中打印。代码如下:
sender = 'tim@abc.com'
recipient = 'tom@xyz.org'
subject = 'Hello!'
print('From: {} To: {} subject: {}'.format(sender, recipient, subject))
目前它的打印方式如下:
From: tim@abc.com To: tom@xyz.org subject: Hello!
但我希望它像这样打印:
From: tim@abc.com
To: tom@xyz.org
subject: Hello!
我认为如果我在print语句中添加“sep”函数就可以打印出来,就像这样:
sender = 'tim@abc.com'
recipient = 'tom@xyz.org'
subject = 'Hello!'
print('From: {} To: {} subject: {}'.format(sender, recipient, subject), sep = '\n')
虽然没有用。有任何想法吗?所有帮助表示赞赏!
答案 0 :(得分:2)
直接在打印字符串中使用'\ n'
a ="aaa"
b="bbb"
c="ccc"
print('From: {}\nTo: {}\nSubject:{}\n'.format(a,b,c))
我明白了:
From: aaa
To: bbb
Subject:ccc
在原始设置中,您只有一个字符串,因此分隔符(即sep)没有任何内容可以分开。
答案 1 :(得分:1)
sep
关键字适用于单独的字符串,如下所示:
>>> print('From: {}', 'To: {}', 'subject: {}', sep = '\n')
From: {}
To: {}
subject: {}
对于集成字符串,只需在字符串中起诉新的行\n
字符:
>>> print('From: {} \nTo: {} \nsubject: {}'.format(sender, recipient, subject))
From: tim@abc.com
To: tom@xyz.org
subject: Hello!