Created
May 17, 2019 02:31
-
-
Save ezirmusitua/bb5d5bc7d8d518a043b69a116a9d9165 to your computer and use it in GitHub Desktop.
[Format string] Format string(string template) #python
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
# 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