5

有人对如何将 tis 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);
}
4

5 回答 5

6

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

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

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

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

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

字符串.模板,例如

string.Template('I like $food').substitute(food="spinach")
于 2012-07-29T17:42:19.260 回答
3

您想在 Python 3 中对字符串使用 format() 方法:

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

或查看 Python 2.X 的字符串插值文档

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

于 2012-07-29T17:31:18.580 回答
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]))
于 2012-07-29T17:47:07.463 回答
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/'
于 2012-07-29T18:09:27.680 回答
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]))
于 2012-07-29T18:09:09.593 回答