本文整理汇总了Python中_string.formatter_parser方法的典型用法代码示例。如果您正苦于以下问题:Python _string.formatter_parser方法的具体用法?Python _string.formatter_parser怎么用?Python _string.formatter_parser使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类_string
的用法示例。
在下文中一共展示了_string.formatter_parser方法的10个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_formatter_parser_errors
# 需要导入模块: import _string [as 别名]
# 或者: from _string import formatter_parser [as 别名]
def test_formatter_parser_errors(self):
errors = [ ("{0!", "unmatched '{' in format spec" if is_cli else "end of string while looking for conversion specifier"),
("}a{", "Single '}' encountered in format string"),
("{0:0.1a", "unmatched '{' in format spec"),
("{0:{}", "unmatched '{' in format spec"),
("{0:aa{ab}", "unmatched '{' in format spec"),
("{0!}", "end of format while looking for conversion specifier" if is_cli else "unmatched '{' in format spec"),
("{0!", "unmatched '{' in format spec" if is_cli else "end of string while looking for conversion specifier"),
("{0!aa}", "expected ':' after format specifier" if is_cli else "expected ':' after conversion specifier"),
("{0.{!:{.}.}}", "expected ':' after format specifier" if is_cli else "unexpected '{' in field name"),
("{", "Single '{' encountered in format string"),
]
if is_cli: # https://github.com/IronLanguages/ironpython3/issues/867
errors += [
("{0!}}", "end of format while looking for conversion specifier"),
]
else:
_string.formatter_parser("{0!}}")
for format, errorMsg in errors:
self.assertRaisesMessage(ValueError, errorMsg, list, _string.formatter_parser(format))
示例2: __init__
# 需要导入模块: import _string [as 别名]
# 或者: from _string import formatter_parser [as 别名]
def __init__(self, format_string, default=None):
self.default = default
self.result = []
self.fields = []
for literal_text, field_name, format_spec, conversion in \
_string.formatter_parser(format_string):
if literal_text:
self.result.append(literal_text)
if field_name:
self.fields.append((
len(self.result),
self._field_access(field_name, format_spec, conversion),
))
self.result.append("")
if len(self.result) == 1:
if self.fields:
self.format_map = self.fields[0][1]
else:
self.format_map = lambda _: format_string
del self.result, self.fields
示例3: safe_substitute
# 需要导入模块: import _string [as 别名]
# 或者: from _string import formatter_parser [as 别名]
def safe_substitute(self, *args, **kws):
if len(args) > 1:
raise TypeError('Too many positional arguments')
if not args:
mapping = kws
elif kws:
mapping = ChainMap(kws, args[0])
else:
mapping = args[0]
# Helper function for .sub()
def convert(mo):
named = mo.group('named') or mo.group('braced')
if named is not None:
try:
# We use this idiom instead of str() because the latter
# will fail if val is a Unicode containing non-ASCII
return '%s' % (mapping[named],)
except KeyError:
return mo.group()
if mo.group('escaped') is not None:
return self.delimiter
if mo.group('invalid') is not None:
return mo.group()
raise ValueError('Unrecognized named group in pattern',
self.pattern)
return self.pattern.sub(convert, self.template)
########################################################################
# the Formatter class
# see PEP 3101 for details and purpose of this class
# The hard parts are reused from the C implementation. They're exposed as "_"
# prefixed methods of str.
# The overall parser is implemented in _string.formatter_parser.
# The field name parser is implemented in _string.formatter_field_name_split
示例4: parse
# 需要导入模块: import _string [as 别名]
# 或者: from _string import formatter_parser [as 别名]
def parse(self, format_string):
return _string.formatter_parser(format_string)
# given a field_name, find the object it references.
# field_name: the field being looked up, e.g. "0.name"
# or "lookup[3]"
# used_args: a set of which args have been used
# args, kwargs: as passed in to vformat
示例5: test_formatter_parser
# 需要导入模块: import _string [as 别名]
# 或者: from _string import formatter_parser [as 别名]
def test_formatter_parser(self):
def parse(format):
return list(_string.formatter_parser(format))
formatter = parse("prefix {2!s}xxx{0:^+10.3f}{obj.attr!s} {z[0]!s:10}")
self.assertEqual(formatter, [
('prefix ', '2', '', 's'),
('xxx', '0', '^+10.3f', None),
('', 'obj.attr', '', 's'),
(' ', 'z[0]', '10', 's'),
])
formatter = parse("prefix {} suffix")
self.assertEqual(formatter, [
('prefix ', '', '', None),
(' suffix', None, None, None),
])
formatter = parse("str")
self.assertEqual(formatter, [
('str', None, None, None),
])
formatter = parse("")
self.assertEqual(formatter, [])
formatter = parse("{0}")
self.assertEqual(formatter, [
('', '0', '', None),
])
self.assertRaises(TypeError, _string.formatter_parser, 1)
示例6: safe_substitute
# 需要导入模块: import _string [as 别名]
# 或者: from _string import formatter_parser [as 别名]
def safe_substitute(*args, **kws):
if not args:
raise TypeError("descriptor 'safe_substitute' of 'Template' object "
"needs an argument")
self, *args = args # allow the "self" keyword be passed
if len(args) > 1:
raise TypeError('Too many positional arguments')
if not args:
mapping = kws
elif kws:
mapping = _ChainMap(kws, args[0])
else:
mapping = args[0]
# Helper function for .sub()
def convert(mo):
named = mo.group('named') or mo.group('braced')
if named is not None:
try:
return str(mapping[named])
except KeyError:
return mo.group()
if mo.group('escaped') is not None:
return self.delimiter
if mo.group('invalid') is not None:
return mo.group()
raise ValueError('Unrecognized named group in pattern',
self.pattern)
return self.pattern.sub(convert, self.template)
########################################################################
# the Formatter class
# see PEP 3101 for details and purpose of this class
# The hard parts are reused from the C implementation. They're exposed as "_"
# prefixed methods of str.
# The overall parser is implemented in _string.formatter_parser.
# The field name parser is implemented in _string.formatter_field_name_split
示例7: test_formatter_parser
# 需要导入模块: import _string [as 别名]
# 或者: from _string import formatter_parser [as 别名]
def test_formatter_parser(self):
tests = [ ('{0.}', [('', '0.', '', None)]),
('{0:.{abc}}', [('', '0', '.{abc}', None)]),
('{0[]}', [('', '0[]', '', None)]),
('{0!!}', [('', '0', '', '!')]),
('{0:::!!::!::}', [('', '0', '::!!::!::', None)]),
('{0.]}', [('', '0.]', '', None)]),
('{0..}', [('', '0..', '', None)]),
('{{', [('{', None, None, None)]),
('}}', [('}', None, None, None)]),
('{{}}', [('{', None, None, None), ('}', None, None, None)]),
]
for format, expected in tests:
self.assertEqual(list(_string.formatter_parser(format)), expected)
tests = [
('{0.{:{.}.}}', [('', '0.{', '{.}.}', None)]),
('{0.{:.}.}', [('', '0.{', '.}.', None)]),
('{0.{!.:{.}.}}', [('', '0.{', '{.}.}', '.')]),
('{0.{!!:{.}.}}', [('', '0.{', '{.}.}', '!')]),
('{0[}', [('', '0[', '', None)]),
('{0.[}', [('', '0.[', '', None)]),
]
for format, expected in tests:
if is_cli: # https://github.com/IronLanguages/ironpython3/issues/867
self.assertEqual(list(_string.formatter_parser(format)), expected)
else:
with self.assertRaises(ValueError):
list(_string.formatter_parser(format))
示例8: execute
# 需要导入模块: import _string [as 别名]
# 或者: from _string import formatter_parser [as 别名]
def execute(self) -> DataFrame:
"""
Returns a DataFrame for which the SQL statement has been executed by
the underlying SQL engine.
>>> str0 = 'abc'
>>> ks.sql("select {str0}")
abc
0 abc
>>> str1 = 'abc"abc'
>>> str2 = "abc'abc"
>>> ks.sql("select {str0}, {str1}, {str2}")
abc abc"abc abc'abc
0 abc abc"abc abc'abc
>>> strs = ['a', 'b']
>>> ks.sql("select 'a' in {strs} as cond1, 'c' in {strs} as cond2")
cond1 cond2
0 True False
"""
blocks = _string.formatter_parser(self._statement)
# TODO: use a string builder
res = ""
try:
for (pre, inner, _, _) in blocks:
var_next = "" if inner is None else self._convert(inner)
res = res + pre + var_next
self._normalized_statement = res
sdf = self._session.sql(self._normalized_statement)
finally:
for v in self._temp_views:
self._session.catalog.dropTempView(v)
return DataFrame(sdf)
示例9: safe_substitute
# 需要导入模块: import _string [as 别名]
# 或者: from _string import formatter_parser [as 别名]
def safe_substitute(*args, **kws):
if not args:
raise TypeError("descriptor 'safe_substitute' of 'Template' object "
"needs an argument")
self, *args = args # allow the "self" keyword be passed
if len(args) > 1:
raise TypeError('Too many positional arguments')
if not args:
mapping = kws
elif kws:
mapping = ChainMap(kws, args[0])
else:
mapping = args[0]
# Helper function for .sub()
def convert(mo):
named = mo.group('named') or mo.group('braced')
if named is not None:
try:
# We use this idiom instead of str() because the latter
# will fail if val is a Unicode containing non-ASCII
return '%s' % (mapping[named],)
except KeyError:
return mo.group()
if mo.group('escaped') is not None:
return self.delimiter
if mo.group('invalid') is not None:
return mo.group()
raise ValueError('Unrecognized named group in pattern',
self.pattern)
return self.pattern.sub(convert, self.template)
########################################################################
# the Formatter class
# see PEP 3101 for details and purpose of this class
# The hard parts are reused from the C implementation. They're exposed as "_"
# prefixed methods of str.
# The overall parser is implemented in _string.formatter_parser.
# The field name parser is implemented in _string.formatter_field_name_split
示例10: safe_substitute
# 需要导入模块: import _string [as 别名]
# 或者: from _string import formatter_parser [as 别名]
def safe_substitute(*args, **kws):
if not args:
raise TypeError("descriptor 'safe_substitute' of 'Template' object "
"needs an argument")
self, *args = args # allow the "self" keyword be passed
if len(args) > 1:
raise TypeError('Too many positional arguments')
if not args:
mapping = kws
elif kws:
mapping = _ChainMap(kws, args[0])
else:
mapping = args[0]
# Helper function for .sub()
def convert(mo):
named = mo.group('named') or mo.group('braced')
if named is not None:
try:
# We use this idiom instead of str() because the latter
# will fail if val is a Unicode containing non-ASCII
return '%s' % (mapping[named],)
except KeyError:
return mo.group()
if mo.group('escaped') is not None:
return self.delimiter
if mo.group('invalid') is not None:
return mo.group()
raise ValueError('Unrecognized named group in pattern',
self.pattern)
return self.pattern.sub(convert, self.template)
########################################################################
# the Formatter class
# see PEP 3101 for details and purpose of this class
# The hard parts are reused from the C implementation. They're exposed as "_"
# prefixed methods of str.
# The overall parser is implemented in _string.formatter_parser.
# The field name parser is implemented in _string.formatter_field_name_split