當前位置: 首頁>>代碼示例>>Python>>正文


Python _string.formatter_parser方法代碼示例

本文整理匯總了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)) 
開發者ID:IronLanguages,項目名稱:ironpython3,代碼行數:24,代碼來源:test_strformat.py

示例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 
開發者ID:mikf,項目名稱:gallery-dl,代碼行數:24,代碼來源:util.py

示例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 
開發者ID:war-and-code,項目名稱:jawfish,代碼行數:40,代碼來源:string.py

示例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 
開發者ID:war-and-code,項目名稱:jawfish,代碼行數:11,代碼來源:string.py

示例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) 
開發者ID:Microvellum,項目名稱:Fluid-Designer,代碼行數:34,代碼來源:test_unicode.py

示例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 
開發者ID:CedricGuillemet,項目名稱:Imogen,代碼行數:42,代碼來源:string.py

示例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)) 
開發者ID:IronLanguages,項目名稱:ironpython3,代碼行數:33,代碼來源:test_strformat.py

示例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) 
開發者ID:databricks,項目名稱:koalas,代碼行數:37,代碼來源:sql.py

示例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 
開發者ID:Microvellum,項目名稱:Fluid-Designer,代碼行數:44,代碼來源:string.py

示例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 
開發者ID:ShikyoKira,項目名稱:Project-New-Reign---Nemesis-Main,代碼行數:44,代碼來源:string.py


注:本文中的_string.formatter_parser方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。