【问题标题】:How can I interpolate variables in Python heredocs?如何在 Python heredocs 中插入变量?
【发布时间】: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 中进行插值非常感兴趣。

【问题讨论】:

标签: python heredoc string-interpolation


【解决方案1】:

在许多语言中称为“heredocs”的内容在 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

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

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

【讨论】:

    【解决方案2】:

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

    a = 42
    b = 23
    
    s1 = """
    some {} foo
    with {}
    """.format(a, b)
    
    print(s1)
    
    s2 = """
    some %s foo
    with %s
    """ % (a, b)
    
    print(s2)
    

    【讨论】:

    • 太棒了!这些将适用于 3.6 之前的 Python 版本。
    猜你喜欢
    • 2015-10-17
    • 2022-12-03
    • 1970-01-01
    • 2022-11-03
    • 2013-11-14
    • 1970-01-01
    • 2017-11-11
    • 2016-08-10
    • 1970-01-01
    相关资源
    最近更新 更多