Created
September 29, 2014 09:51
-
-
Save shihpeng/115dc911a67963ea3af8 to your computer and use it in GitHub Desktop.
Best way to do Python string format
This file contains 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
# Python 2.6+ | |
# After Python 2.6, you can choose to use .format() function or the old %. | |
>>> '{0}, {1}, {2}'.format('a', 'b', 'c') | |
'a, b, c' | |
>>> '{2}, {1}, {0}'.format('a', 'b', 'c') | |
'c, b, a' | |
>>> '{2}, {1}, {0}'.format(*'abc') # unpacking argument sequence | |
'c, b, a' | |
>>> '{0}{1}{0}'.format('abra', 'cad') # arguments' indices can be repeated | |
'abracadabra' | |
>>> 'Coordinates: {latitude}, {longitude}'.format(latitude='37.24N', longitude='-115.81W') | |
'Coordinates: 37.24N, -115.81W' | |
>>> coord = {'latitude': '37.24N', 'longitude': '-115.81W'} | |
>>> 'Coordinates: {latitude}, {longitude}'.format(**coord) | |
'Coordinates: 37.24N, -115.81W' | |
# Python 2.7+ | |
# After Python 2.7, positional argument specifiers can be omitted, '{} {}' is equivalent to '{0} {1}'. | |
>>> '{}, {}, {}'.format('a', 'b', 'c') # 2.7+ only | |
'a, b, c' | |
# ~Python 2.6 | |
# Templates are introduced in Python 2.4, however, Templates make the code verbose and hard to read. | |
>>> from string import Template | |
>>> s = Template('$who likes $what') | |
>>> s.substitute(who='tim', what='kung pao') | |
'tim likes kung pao' | |
>>> d = dict(who='tim') | |
>>> Template('Give $who $100').substitute(d) | |
Traceback (most recent call last): | |
... | |
ValueError: Invalid placeholder in string: line 1, col 11 | |
>>> Template('$who likes $what').substitute(d) | |
Traceback (most recent call last): | |
... | |
KeyError: 'what' | |
>>> Template('$who likes $what').safe_substitute(d) | |
'tim likes $what' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment