Search code examples
pythonheredocstring-interpolation

How can I interpolate variables in Python heredocs?


In Perl languages, I can interpolate in double quoted 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;

How do I do something similar in Python? In searching "heredoc string interpolation Python", I did come across information on Python f-strings, which facilitate string interpolation (for Python 3.6 and later).

Python 3.6+ with f-strings:

#!/bin/env python3

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

All three of the above produce the exact same output:

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

That's all nice and everything, but I'm still really interested in interpolation in heredocs using Python.


Solution

  • Just for the record, the other string formatting options in Python also work for multi-line tripple-quoted strings:

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