Skip to content

Instantly share code, notes, and snippets.

@ezirmusitua
Created May 17, 2019 02:31
Show Gist options
  • Save ezirmusitua/bb5d5bc7d8d518a043b69a116a9d9165 to your computer and use it in GitHub Desktop.
Save ezirmusitua/bb5d5bc7d8d518a043b69a116a9d9165 to your computer and use it in GitHub Desktop.
[Format string] Format string(string template) #python
# referenece: https://realpython.com/python-string-formatting/
# 1. use % operator
'Hello, %s' % name
'Hey %s, there is a 0x%x error!' % (name, errno)
'Hey %(name)s, there is a 0x%(errno)x error!' % { "name": name, "errno": errno }
# 2. use `string.format`
'Hello, {}'.format(name)
'Hey {name}, there is a 0x{errno:x} error!'.format(name=name, errno=errno)
# 3. use `fstring`
f'Hello, {name}!'
f'Five plus ten is {a + b} and not {2 * (a + b)}.'
# 4. use `string.Template`
from string import Template
t = Template('Hey, $name!')
t.substitute(name=name)
tmpl_string = 'Hey $name, there is a $error error!'
Template(tmpl_string).substitute(name=name, error=hex(errno))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment