5

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、例:

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

または、Python2.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 に答える