Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python string interpolation using dictionary and strings

Tags:

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.

like image 969
richid Avatar asked Aug 20 '09 04:08

richid


People also ask

How is string interpolation performed in Python?

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.

How do you use string interpolation?

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}?\

How do you make a string dynamic in Python?

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.

Which strings do interpolate variables?

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.


2 Answers

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 
like image 188
Kenan Banks Avatar answered Oct 30 '22 04:10

Kenan Banks


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.

like image 32
monkut Avatar answered Oct 30 '22 03:10

monkut