9

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.

Christopher Bottoms
  • 11,218
  • 8
  • 50
  • 99
  • 3
    Note, since this specifically deals with heredocs, this is different from the many easy-to-find questions that deal with variable interpolation in Python strings (e.g. https://stackoverflow.com/questions/3542714/variable-interpolation-in-python). – Christopher Bottoms Apr 17 '18 at 19:27

2 Answers2

14

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)
moritz
  • 12,710
  • 1
  • 41
  • 63
12

What in many languages are known as "heredocs" are typically called "triple-quoted strings" in Python. You simply need to create a triple-quoted f-string:

#!/bin/env python3

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

As you previously noted, however, this is specific to Python 3.6 and later.


If you want to do more than just interpolate variables, f-strings also provide evaluation of code inside curly braces:

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

This is very similar to double quoted strings in Raku (F.K.A. Perl 6):

#!/bin/env perl6
put "5+7 = {5 + 7}";
5+7 = 12
Christopher Bottoms
  • 11,218
  • 8
  • 50
  • 99