Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python equivalent for sprintf

Does someone have a nice tip how to port tis PHP function to python?

/**
 * converts id (media id) to the corresponding folder in the data-storage
 * eg: default mp3 file with id 120105 is stored in
 * /(storage root)/12/105/default.mp3
 * if absolute paths are needed give path for $base
 */

public static function id_to_location($id, $base = FALSE)
{
    $idl = sprintf("%012s",$id);
    return $base . (int)substr ($idl,0,4) . '/'. (int)substr($idl,4,4) . '/' . (int)substr ($idl,8,4);
}
like image 923
ohrstrom Avatar asked Jul 29 '12 17:07

ohrstrom


Video Answer


2 Answers

For python 2.x, you have these options:

[best option] The newer str.format and the full format specification, e.g.

"I like {food}".format(food="chocolate")

The older interpolation formatting syntax e.g.

"I like %s" % "berries"
"I like %(food)s" % {"food": "cheese"}

string.Template, e.g.

string.Template('I like $food').substitute(food="spinach")
like image 119
orip Avatar answered Oct 31 '22 19:10

orip


You want to use the format() method for strings in Python 3:

http://docs.python.org/library/string.html#formatstrings

or check the string interpolation documentation for Python 2.X

http://docs.python.org/library/stdtypes.html

like image 38
Andreas Jung Avatar answered Oct 31 '22 18:10

Andreas Jung