如何在Python heredocs中插入变量?

时间:2018-04-17 19:12:04

标签: python heredoc string-interpolation

在Perl语言中,我可以用双引号heredocs进行插值:

的Perl:

#!/bin/env perl
use strict;
use warnings;

my $job  = 'foo';
my $cpus = 3;

my $heredoc = <<"END";
#SBATCH job $job
#SBATCH cpus-per-task $cpus
END

print $heredoc;

Rakudo Perl 6:

#!/bin/env perl6

my $job  = 'foo';
my $cpus = 3;

my $heredoc = qq:to/END/;
    #SBATCH job $job
    #SBATCH cpus-per-task $cpus
    END

print $heredoc;

我如何在Python中做类似的事情?在搜索&#34; heredoc字符串插值Python&#34;时,我确实遇到了Python f字符串的信息,这有助于字符串插值(适用于Python 3.6及更高版本)。

带有f-strings的Python 3.6+:

#!/bin/env python3

job  = 'foo'
cpus = 3
print(f"#SBATCH job {job}")
print(f"#SBATCH cpus-per-task {cpus}")

上述所有三个产生完全相同的输出:

#SBATCH job cutadapt
#SBATCH cpus-per-task 3

这一切都很好,但是我仍然对使用Python的 heredocs 中的插值感兴趣。

2 个答案:

答案 0 :(得分:6)

大多数人会称之为&#34; heredocs&#34;被称为&#34;三重引用的字符串&#34;在Python中。您只需创建一个triple-quoted f-string

#!/bin/env python3

cpus = 3
job  = 'foo'
print(f'''\
#SBATCH job {job}
#SBATCH cpus-per-task {cpus}''')

然而,如前所述,这是Python 3.6及更高版本所特有的。

如果你想做的不仅仅是内插变量,f-strings还提供了大括号内代码的评估:

#!/bin/env python3
print(f'5+7 = {5 + 7}')
5+7 = 12

这与Perl 6中的双引号字符串非常相似:

#!/bin/env perl6
put "5+7 = {5 + 7}";
5+7 = 12

答案 1 :(得分:5)

仅为了记录,Python中的其他字符串格式化选项也适用于多行三重引用的字符串:

a = 42
b = 23

s1 = """
some {} foo
with {}
""".format(a, b)

print(s1)

s2 = """
some %s foo
with %s
""" % (a, b)

print(s2)