加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

与Perl中的字典相对应的Python字符串格式,带有哈希

发布时间:2020-12-15 23:22:03 所属栏目:大数据 来源:网络整理
导读:我喜欢 Python用字典格式化字符串的方式: print "%(key1)s and %(key2)s" % aDictObj 我想用Perl在Perl中实现同样的功能.是否有任何代码段或小型库可以执行此操作? 编辑: 谢谢你试试这个答案.至于我,我出了一小段代码: sub dict_replace{ my ($tempStr,$
我喜欢 Python用字典格式化字符串的方式:

print "%(key1)s and %(key2)s" % aDictObj

我想用Perl在Perl中实现同样的功能.是否有任何代码段或小型库可以执行此操作?

编辑:

谢谢你试试这个答案.至于我,我出了一小段代码:

sub dict_replace
{
    my ($tempStr,$tempHash) = @_;
    my $key;

    foreach $key (sort keys %$tempHash) {
        my $tmpTmp = $tempHash->{$key};
        $tempStr =~ s/%($key)s/$tmpTmp/g;
    }

    return $tempStr;
}

它只是有效.这不像使用字典的Python字符串格式那样功能完整,但我想改进它.

解决方法

从python文档:

The effect is similar to the using sprintf() in the C language.

所以这是使用printfsprintf的解决方案

my @ordered_list_of_values_to_print = qw(key1 key2);
printf '%s and %s',@ordered_list_of_values_to_print;

还有一个新模块使用命名参数来完成它:

use Text::sprintfn;
my %dict = (key1 => 'foo',key2 => 'bar');
printfn '%(key1)s and %(key2)s',%dict;

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读