sprintf的Python等价物
有人知道如何将PHP函数移植到python吗sprintf的Python等价物,python,hash,directory,Python,Hash,Directory,有人知道如何将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 */ pu
/**
* 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);
}
您希望对Python 3中的字符串使用format()方法:
或者查看Python 2.X的字符串插值文档
对于python 2.x,您有以下选项: [最佳选项]更新的和完整的,例如 较旧的语法,例如
"I like %s" % "berries"
"I like %(food)s" % {"food": "cheese"}
,例如
好的-找到了一个方法-我认为不是很好,但工作
def id_to_location(id):
l = "%012d" % id
return '/%d/%d/%d/' % (int(l[0:4]), int(l[4:8]), int(l[8:12]))
可以使用默认参数引入基准。也许你想要这样:
def id_to_location(id,base=""):
l = "%012d" % id
return '%s/%d/%d/%d/' % (base,int(l[0:4]), int(l[4:8]), int(l[8:12]))
在一行中,(Python 2.x):
然后:
def id_to_location(id):
l = "%012d" % id
return '/%d/%d/%d/' % (int(l[0:4]), int(l[4:8]), int(l[8:12]))
def id_to_location(id,base=""):
l = "%012d" % id
return '%s/%d/%d/%d/' % (base,int(l[0:4]), int(l[4:8]), int(l[8:12]))
id_to_location = lambda i: '/%d/%d/%d/' % (int(i)/1e8, int(i)%1e8/1e4, int(i)%1e4)
print id_to_location('001200230004')
'/12/23/4/'