Skip to content

Instantly share code, notes, and snippets.

@tho
Created August 7, 2016 01:26
Show Gist options
  • Save tho/a4e8f557181cf3a1099b2cc11dba0873 to your computer and use it in GitHub Desktop.
Save tho/a4e8f557181cf3a1099b2cc11dba0873 to your computer and use it in GitHub Desktop.
Python is_format_string() predicate
def is_format_string(s):
"""Test if the given string is a format string.
Args:
s (str): String to test.
Returns:
bool: True if `s` is a format string, False otherwise.
Bugs:
The string '{}{' is considered a format string since the IndexError is
raised before the ValueError. The same applies to '{}}'.
Examples:
>>> is_format_string()
Traceback (most recent call last):
TypeError: is_format_string() takes exactly 1 argument (0 given)
>>> is_format_string(None)
False
>>> is_format_string('')
False
>>> is_format_string('foo')
False
>>> is_format_string('{')
False
>>> is_format_string('{{')
False
>>> is_format_string('}')
False
>>> is_format_string('}}')
False
>>> is_format_string('{{}}')
False
>>> is_format_string('{}')
True
>>> is_format_string('{foo}')
True
"""
try:
str.format(s)
except (IndexError, KeyError):
# s = '{}':
# IndexError: tuple index out of range
# s = '{foo}':
# KeyError: 'foo'
return True
except (TypeError, ValueError):
# s = None:
# TypeError: descriptor 'format' requires a 'str' object but
# received a 'NoneType'
# s = '{'
# ValueError: Single '{' encountered in format string
return False
else:
return False
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment