2012-07-29 58 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]))