Separating string into two or more strings
Like Eugene Yarmash explained in his answer you can't mix ordinary and mapping format specifiers in same string, but you could separate it to two (or more) strings like this:
'%s' % datetime + ' %(type)s %(host)s' % dictionary["_source"]
This will work but if you wanted to print datetime in the middle (something like this '%(type)s %s %(host)s') or if you have more ordinary and mapping format specifiers which are intertwined (something like this '%s '%(type)s %s %(host)s' %s). You could separate '%(type)s %s %(host)s' into multiple strings like this:
'%(type)s' % dictionary["_source"] + ' %s ' % datetime + '%(host)s' % dictionary["_source"]
But then there is no point in string format in first place.
First applying mapping than ordinary format specifiers
This method solves our problem of formatting string with ordinary and mapping format specifiers which are intertwined. I will explain this method on the example from OP. We have string '%s %(type)s %(host)s' which we want to format. Like I said in first we apply mapping format specifiers:
print('%s %(type)s %(host)s' % dictionary["_source"])
If we do this it will print out:
'{'type': 'type', 'host': 'host'} type host'
This does not work, but what we can do is add parentheses () in every ordinary format specifier and update our dictionary with {'': '%s'}:
print('%()s %(type)s %(host)s' % {'type': 'type', 'host': 'host', '': '%s'})
This will print out:
'%s type host'
which we can easily format with % (datetime).
The question is how to {'': '%s'} to your dictionary. You have two options, to use a function or to define your class for the dictionary object.
1. Using function
def ForFormat(x):
d = x.copy()
d.update({'': '%s'})
return d
And you use it like this:
print('%()s %(type)s %(host)s' % ForFormat(dictionary["_source"]) % (datetime))
The result is exactly what we want:
'25-08-2017 10:26:11 type 45 host'
2. Creating class
class FormatDict(dict):
def __missing__(self, key):
return '%s'
Here we don't actually add {'': '%s'} to dictionary, but rather change its method __missing__() which is called when key can not be found in dictionary so it will retrun '%s' for each mapping format specifier that is not in dictionary. It is used like this:
print('%()s %(type)s %(host)s' % FormatDict(dictionary["_source"]) % (datetime))
It also prints out the desired result:
'25-08-2017 10:26:11 type 45 host'
format:print("{0} {1[host]} {1[type]}".format(datetime,dictionary["_source"]))Read more aboutformathere