Python相当于sprintf

ohr*_*rom 4 python directory hash

有人有一个很好的提示如何将PHP函数移植到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);
}
Run Code Online (Sandbox Code Playgroud)

ori*_*rip 5

对于python 2.x,您有以下选项:

[最佳选择]较新的str.format和完整格式规范,例如

"I like {food}".format(food="chocolate")
Run Code Online (Sandbox Code Playgroud)

较旧的插值格式化语法,例如

"I like %s" % "berries"
"I like %(food)s" % {"food": "cheese"}
Run Code Online (Sandbox Code Playgroud)

string.Template,例如

string.Template('I like $food').substitute(food="spinach")
Run Code Online (Sandbox Code Playgroud)