Skip to content

Instantly share code, notes, and snippets.

@ashafer01
Created January 17, 2019 17:22
Show Gist options
  • Save ashafer01/25efae3d786fb52b4169bd3e89d8b486 to your computer and use it in GitHub Desktop.
Save ashafer01/25efae3d786fb52b4169bd3e89d8b486 to your computer and use it in GitHub Desktop.
Python custom string.Formatter example
import string
class MyForm(string.Formatter):
def parse(self, format_string):
for tpl in string.Formatter.parse(self, format_string):
print(tpl)
literal_text, field_name, format_spec, conversion = tpl
if field_name:
literal_text += f'"{field_name}"'
yield literal_text, None, None, None
else:
yield tpl
fmt = '{abc} {def} {3} {4} foo bar not in brackets {hello} {5,7} end'
print(fmt)
x = MyForm()
print(x.format(fmt))
"""
{abc} {def} {3} {4} foo bar not in brackets {hello} {5,7} end
('', 'abc', '', None)
(' ', 'def', '', None)
(' ', '3', '', None)
(' ', '4', '', None)
(' foo bar not in brackets ', 'hello', '', None)
(' ', '5,7', '', None)
(' end', None, None, None)
"abc" "def" "3" "4" foo bar not in brackets "hello" "5,7" end
"""
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment