【发布时间】:2018-09-27 21:00:29
【问题描述】:
在 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-strings 的信息,这有助于字符串插值(适用于 Python 3.6 及更高版本)。
带有 f 字符串的 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 中进行插值非常感兴趣。
【问题讨论】:
-
注意,由于这专门处理 heredocs,这与处理 Python 字符串中的变量插值的许多易于查找的问题不同(例如 stackoverflow.com/questions/3542714/…)。
标签: python heredoc string-interpolation