sprin的Python等价物

2024-06-18 19:15:30 发布

您现在位置:Python中文网/ 问答频道 /正文

有人知道如何将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);
}

Tags: theto函数iniddefaultbasestorage
3条回答

在一行中(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/'

您想对Python3中的字符串使用format()方法:

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

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

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

对于Python2.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")

相关问题 更多 >