2017-08-25 38 views
1

我有一个字典和一个日期时间对象,我转换为字符串。如何从同一行中的字典中打印日期时间字符串和多个项目?字符串和字典在同一行的Python字符串插值

例如:

dictionary = {"_source": {"host": "host", "type": "type"}} 
datetime = '25-08-2017 10:26:11' 

这就是我想要打印:

print("%s %(host)s %(type)s" % (datetime,dictionary["_source"])) 

的时间字符串得到一个错误:

TypeError: format requires a mapping 

谢谢!

+0

你可以添加你是什么什么这个例子输出? '25 -08-2017 10:26:11主机类型'? – ands

+1

这里是你如何使用'format'来完成它:'print(“{0} {1 [host]} {1 [type]}”。format(datetime,dictionary [“_ source”]))'Read more about'格式'[here](https://docs.python.org/3.4/library/string.html#formatspec) –

回答

1

像其他人一样表示,它可能是最好的使用str.format()。与方法str.format()最接近的选项,你的问题是 Violet Red在他answer建议代码:

"{} {host} {type}".format(datetime,**dictionary["_source"]) 

但如果你真的想要或需要使用的格式(使用%)的老办法,那么你可以尝试一些这些选项:

  • 分离字符串转换成两个或多个字符串

    Eugene Yarmash在他answer解释不能混用在同一串普通和映射格式说明,但你可以单独给两个(或更多)的字符串是这样的:

    '%s' % datetime + ' %(type)s %(host)s' % dictionary["_source"] 
    

    这会工作,但如果你想在中间打印datetime(如'%(type)s %s %(host)s'),或者如果您有更多的交织在一起的普通和映射格式说明符(如'%s '%(type)s %s %(host)s' %s)。你可以分开'%(type)s %s %(host)s'分为多个字符串是这样的:

    '%(type)s' % dictionary["_source"] + ' %s ' % datetime + '%(host)s' % dictionary["_source"] 
    

    但再有就是在字符串格式在首位没有意义的。比普通的格式说明

  • 首先应用映射该方法解决了我们与相互交织普通和映射格式说明符格式化字符串的问题。我将在OP的例子中解释这个方法。我们有我们想要格式化的字符串'%s %(type)s %(host)s'。就像我在第一次说我们应用的映射格式说明:

    print('%s %(type)s %(host)s' % dictionary["_source"]) 
    

    如果我们做到这一点会打印出:

    '{'type': 'type', 'host': 'host'} type host' 
    

    这是不行的,但我们可以做的就是添加括号()每普通格式说明和更新我们的字典与{'': '%s'}

    print('%()s %(type)s %(host)s' % {'type': 'type', 'host': 'host', '': '%s'}) 
    

    这将打印出:

    '%s type host'

    我们可以很容易地用% (datetime)进行格式化。

    问题是如何{'': '%s'}到您的字典。你有两个选择,使用一个函数或为字典对象定义你的类。

    1。使用功能

    def ForFormat(x): 
        d = x.copy() 
        d.update({'': '%s'}) 
        return d 
    

    并且你使用这样的:

    print('%()s %(type)s %(host)s' % ForFormat(dictionary["_source"]) % (datetime)) 
    

    结果正是我们所想要的:

    '25-08-2017 10:26:11 type 45 host' 
    

    2.创建类

    class FormatDict(dict): 
        def __missing__(self, key): 
         return '%s' 
    

    这里我们实际上并没有将{'': '%s'}添加到字典中,而是更改其方法__missing__(),这是在字典中找不到密钥时调用的,因此它将针对每个不在字典中的映射格式说明符执行'%s'。它是这样使用:

    print('%()s %(type)s %(host)s' % FormatDict(dictionary["_source"]) % (datetime)) 
    

    还打印出想要的结果:

    '25-08-2017 10:26:11 type 45 host' 
    
3

你最好不要使用format方法:

>>> "{} {d[host]} {d[type]}".format(datetime, d=dictionary["_source"]) 
'25-08-2017 10:26:11 host type' 
6

一种方式是一个名称分配给您的日期时间ARG:

"{t} {host} {type}".format(t=datetime,**dictionary["_source"]) 

但实际上它仍然工作,没有它

"{} {host} {type}".format(datetime,**dictionary["_source"]) 

尽管最好在格式化的字符串中使用命名值imo

0

你可以试试这个:

dictionary = {"_source": {"host": "host", "type": "type"}} 
datetime = '25-08-2017 10:26:11' 

print("host {} type {} datetime {}".format(dictionary["_source"]["host"], dictionary["_source"]["type"], datetime)) 
1

在一个单一的格式字符串不能混淆普通和映射格式说明。您应该使用

"%s %s %s" % (param1, param2, param3) 

"%(key1)s %(key2)s %(key3)s" % {"key1": val1, "key2": val2, "key3": val3} 

在Python 3.6或更高版本,你可以使用更方便和高效的插值f-strings,如:

f'{val1} {val2} {val3}' 

在替代性领域是表达式在运行时进行评估。

相关问题