Say I've got a dictionary with dots in the name of fields, like {'person.name': 'Joe'}
. If I wanted to use this in str.format
, is it possible?
My first instinct was
'Name: {person.name}'.format(**{'person.name': 'Joe'})
but this would only work if my dict were shaped like
{'person':{'name':Joe}}
The relevant manual docs section doesn't mention anyway of escaping the dot.
(Sidenote: I thought that generally
def func(**kw): print(kw)
func(**{'a.b': 'Joe'})
would cause an error, but the **
-expanded function call seems to work even if they're not valid identifiers! It does error out on non-strings though. o_O)
A variable name in R programming language can contain numeric and alphabets along with special characters like dot (.) and underline (-).
Python's str. format() technique of the string category permits you to try and do variable substitutions and data formatting. This enables you to concatenate parts of a string at desired intervals through point data format.
I had similar issue and I solved it by inheriting from string.Formatter
:
import string
class MyFormatter(string.Formatter):
def get_field(self, field_name, args, kwargs):
return (self.get_value(field_name, args, kwargs), field_name)
however you can't use str.format()
because it's still pointing to old formatter and you need to go like this
>>> MyFormatter().vformat("{a.b}", [], {'a.b': 'Success!'})
'Success!'
'Name: {0[person.name]}'.format({'person.name': 'Joe'})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With