首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >sprintf的Python等效项

sprintf的Python等效项
EN

Stack Overflow用户
提问于 2012-07-30 01:23:36
回答 5查看 9.7K关注 0票数 5

有没有人有一个很好的技巧,如何将PHP函数移植到python?

代码语言:javascript
复制
/**
 * 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);
}
EN

回答 5

Stack Overflow用户

回答已采纳

发布于 2012-07-30 02:09:28

在一行代码(Python 2.x)中:

代码语言:javascript
复制
id_to_location = lambda i: '/%d/%d/%d/' % (int(i)/1e8, int(i)%1e8/1e4, int(i)%1e4)

然后:

代码语言:javascript
复制
print id_to_location('001200230004')
'/12/23/4/'
票数 1
EN

Stack Overflow用户

发布于 2012-07-30 01:42:19

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

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

代码语言:javascript
复制
"I like {food}".format(food="chocolate")

旧的interpolation formatting语法,例如

代码语言:javascript
复制
"I like %s" % "berries"
"I like %(food)s" % {"food": "cheese"}

string.Template,例如

代码语言:javascript
复制
string.Template('I like $food').substitute(food="spinach")
票数 6
EN

Stack Overflow用户

发布于 2012-07-30 01:31:19

您希望对Python 3中的字符串使用format()方法:

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

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

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

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/11711315

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档