Comment detail
文字変換表に基く文字列の変換 (Nested Flatten)(1)で。 oldとnewの文字列長が等しいことが保証されるならこちらの方が簡潔でよさそうです。 (文字列長が異なる場合、string.maketrans()はValueErrorを投げます。)
1 2 | def tr(old, new, str):
return str.translate(string.maketrans(old, new))
|
うーむ、なるほど。(こんなメソッドがあったのか) では、(2)で。
1 2 3 4 5 6 7 8 9 10 11 | import itertools
import re
def tr(old, new, str):
def expand(s):
return re.sub("(.)-(.)", lambda m: "".join(chr(i) for i in xrange(ord(m.group(1)), ord(m.group(2)) + 1)), s)
h = dict(itertools.izip(expand(old), expand(new)))
return "".join(h.get(c, None) or c for c in str)
print tr('qwertyuiop', 'QWERTYUIOP', "typewriter")
print tr('a-ceh-j', 'A-CEH-J', "abcdefghijk")
|
この場合、関数内関数にする必要はなかったかな。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | --- a.py Sun Feb 3 11:56:31 2008
+++ a.py Sun Feb 3 11:58:05 2008
@@ -1,9 +1,10 @@
import itertools
import re
+def expand(s):
+ return re.sub("(.)-(.)", lambda m: "".join(chr(i) for i in xrange(ord(m.group(1)), ord(m.group(2)) + 1)), s)
+
def tr(old, new, str):
- def expand(s):
- return re.sub("(.)-(.)", lambda m: "".join(chr(i) for i in xrange(ord(m.group(1)), ord(m.group(2)) + 1)), s)
h = dict(itertools.izip(expand(old), expand(new)))
return "".join(h.get(c, None) or c for c in str)
|





ocean
#5651()
[
Python
]
Rating1/1=1.00
(1)で。
Rating1/1=1.00-0+
1 reply [ reply ]