如何在 Python heredocs 中插入变量?

How can I interpolate variables in Python heredocs?

在 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;

Raku (F.K.A.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 中执行类似操作?在搜索 "heredoc string interpolation Python" 时,我确实遇到了有关 Python f 字符串的信息,它有助于字符串插值(对于 Python 3.6 及更高版本)。

Python 3.6+ 带 f 弦:

#!/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 中进行插值非常感兴趣。

在许多语言中被称为 "heredocs" 的东西在 Python 中通常被称为 "triple-quoted strings"。您只需要创建一个 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 字符串还提供花括号内代码的计算:

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

这与 Raku (F.K.A.Perl 6) 中的双引号字符串非常相似:

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

郑重声明,Python 中的其他字符串格式化选项也适用于多行三引号字符串:

a = 42
b = 23

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

print(s1)

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

print(s2)