最近有人告诉我,我们可以在Python中打印变量,就像Perl一样.
代替:
print("%s, %s, %s" % (foo, bar, baz))
Run Code Online (Sandbox Code Playgroud)
我们可以这样做:
print("%(foo)s, %(bar)s, %(baz)s" % locals())
Run Code Online (Sandbox Code Playgroud)
像在Perl中那样,在Python中打印变量的方式是不是很简单?我认为第二个解决方案实际上看起来非常好并且使代码更具可读性,但是那里的locals()让它看起来像是一种令人费解的方式.
在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;
Run Code Online (Sandbox Code Playgroud)
Rakudo 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;
Run Code Online (Sandbox Code Playgroud)
我如何在Python中做类似的事情?在搜索"heredoc字符串插值Python"时,我确实遇到了有关Python f字符串的信息,这有助于字符串插值(适用于Python 3.6及更高版本).
带有f-strings的Python 3.6+:
#!/bin/env python3
job = 'foo'
cpus = 3
print(f"#SBATCH job {job}")
print(f"#SBATCH cpus-per-task {cpus}")
Run Code Online (Sandbox Code Playgroud)
以上所有三个都产生完全相同的输出:
Run Code Online (Sandbox Code Playgroud)#SBATCH job cutadapt #SBATCH cpus-per-task …