Skip to content

Instantly share code, notes, and snippets.

@hallazzang
Last active August 29, 2015 14:19
Show Gist options
  • Save hallazzang/1d67d8153a2b65a68bbf to your computer and use it in GitHub Desktop.
Save hallazzang/1d67d8153a2b65a68bbf to your computer and use it in GitHub Desktop.
Python string interpolation example (Like Swift)
import re
import inspect
FORMAT_REGEX = re.compile(r'\\\(([a-zA-Z_]\w*)\)')
def formatted(string, silent=False):
to_be_replaced = FORMAT_REGEX.findall(string)
variables = inspect.stack()[1][0].f_locals
for item in to_be_replaced:
if item in variables:
string = string.replace('\({})'.format(item), str(variables[item]))
elif silent:
string = string.replace('\({})'.format(item), '')
else:
raise NameError('name \'{}\' is not defined'.format(item))
return string
def func_a():
foo = 10
print formatted('foo is \(foo)')
func_b()
def func_b():
bar = 20
print formatted('bar is \(bar)')
print formatted('foo is \(foo) and bar is \(bar)', silent=True)
print formatted('foo is \(foo) and bar is \(bar)', silent=False) # An error occurs!
func_a()
# Output
# foo is 10
# bar is 20
# foo is and bar is 20
# Traceback (most recent call last):
# ...
# NameError: name 'foo' is not defined
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment