Given:
dict = {"path": "/var/blah"} curr = "1.1" prev = "1.0"
What's the best/shortest way to interpolate the string to generate the following:
path: /var/blah curr: 1.1 prev: 1.0
I know this works:
str = "path: %(path)s curr: %(curr)s prev: %(prev)s" % {"path": dict["path"],"curr": curr, "prev": prev}
But I was hoping there is a shorter way, such as:
str = "path: %(path)s curr: %s prev: %s" % (dict, curr, prev)
My apologies if this seems like an overly pedantic question.
String interpolation is a process of injecting value into a placeholder (a placeholder is nothing but a variable to which you can assign data/value later) in a string literal. It helps in dynamically formatting the output in a fancier way. Python supports multiple ways to format string literals.
As the colon (":") has special meaning in an interpolation expression item, to use a conditional operator in an interpolation expression, enclose that expression in parentheses. string name = "Horace"; int age = 34; Console. WriteLine($"He asked, \"Is your name {name}?\
With the release of Python 3.6, we were introduced to F-strings. As their name suggests, F-strings begin with "f" followed by a string literal. We can insert values dynamically into our strings with an identifier wrapped in curly braces, just like we did in the format() method.
String interpolation is common in many programming languages which make heavy use of string representations of data, such as Apache Groovy, Julia, Kotlin, Perl, PHP, Python, Ruby, Scala, Swift, Tcl and most Unix shells.
You can try this:
data = {"path": "/var/blah", "curr": "1.1", "prev": "1.0"} s = "path: %(path)s curr: %(curr)s prev: %(prev)s" % data
And of course you could use the newer (from 2.6) .format string method:
>>> mydict = {"path": "/var/blah"} >>> curr = "1.1" >>> prev = "1.0" >>> >>> s = "path: {0} curr: {1} prev: {2}".format(mydict['path'], curr, prev) >>> s 'path: /var/blah curr: 1.1 prev: 1.0'
Or, if all elements were in the dictionary, you could do this:
>>> mydict = {"path": "/var/blah", "curr": 1.1, "prev": 1.0} >>> "path: {path} curr: {curr} prev: {prev}".format(**mydict) 'path: /var/blah curr: 1.1 prev: 1.0' >>>
From the str.format() documentation:
This method of string formatting is the new standard in Python 3.0, and should be preferred to the % formatting described in String Formatting Operations in new code.
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