2012-07-29 155 views
4

有人有一个很好的提示如何将PHP函数移植到python?python相当于sprintf

/** 
* 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); 
} 

回答

1

在一个行,(Python的2.X):

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/' 
5
串插文档

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

[最佳选项]较新的str.format和完整的format specification,例如,

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

旧的interpolation formatting语法例如

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

string.Template例如,

string.Template('I like $food').substitute(food="spinach") 
2

好吧 - 发现了一种方法 - 不是很好,我认为,但做这项工作...

def id_to_location(id): 
    l = "%012d" % id 
    return '/%d/%d/%d/' % (int(l[0:4]), int(l[4:8]), int(l[8:12])) 
0

您可以用缺省参数的基础带来的。也许你希望它是这样的:

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]))