Created
June 24, 2011 16:32
-
-
Save g-k/1045150 to your computer and use it in GitHub Desktop.
Python string formatting eval
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
PINK = '\033[95m' | |
BLUE = '\033[94m' | |
GREEN = '\033[92m' | |
YELLOW = '\033[93m' | |
RED = '\033[91m' | |
ENDC = '\033[0m' | |
for i in range(0, 10, 2): | |
print "{0} {1:^{2}}{3}".format(RED, '(', i, ENDC) | |
from datetime import datetime | |
import string | |
class ForIn(object): | |
def __format__(self, s): | |
loop, template = s.split(':', 1) | |
var_name, method = map(string.strip, loop.split('in', 1)) | |
method, args = method.split('(', 1) | |
args = args.strip(')') | |
method = getattr(locals(), method, None) or \ | |
getattr(globals(), method, None) or \ | |
getattr(__builtins__, method, None) | |
if method: | |
s = '' | |
for var in method(int(args)): | |
locals()[var_name] = var | |
s += template.format(**locals()) | |
return s | |
class Eval(object): | |
def __format__(self, s): | |
return str(eval(s)) | |
print """{For: i in range(10):<li>{{i}}</li>}{Eval: RED + 'dog' + ENDC}""".format(For=ForIn(), Eval=Eval()) | |
print "Today is: {0:%H %M:%S}".format(datetime.now()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment