当前位置: 首页>>代码示例>>Python>>正文


Python string.Formatter方法代码示例

本文整理汇总了Python中string.Formatter方法的典型用法代码示例。如果您正苦于以下问题:Python string.Formatter方法的具体用法?Python string.Formatter怎么用?Python string.Formatter使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在string的用法示例。


在下文中一共展示了string.Formatter方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: format_field

# 需要导入模块: import string [as 别名]
# 或者: from string import Formatter [as 别名]
def format_field(self, value, format_spec):
            if hasattr(value, "__html_format__"):
                rv = value.__html_format__(format_spec)
            elif hasattr(value, "__html__"):
                if format_spec:
                    raise ValueError(
                        "Format specifier {0} given, but {1} does not"
                        " define __html_format__. A class that defines"
                        " __html__ must define __html_format__ to work"
                        " with format specifiers.".format(format_spec, type(value))
                    )
                rv = value.__html__()
            else:
                # We need to make sure the format spec is unicode here as
                # otherwise the wrong callback methods are invoked.  For
                # instance a byte string there would invoke __str__ and
                # not __unicode__.
                rv = string.Formatter.format_field(self, value, text_type(format_spec))
            return text_type(self.escape(rv)) 
开发者ID:remg427,项目名称:misp42splunk,代码行数:21,代码来源:__init__.py

示例2: opensearch_convert

# 需要导入模块: import string [as 别名]
# 或者: from string import Formatter [as 别名]
def opensearch_convert(url):
    """Convert a basic OpenSearch URL into something qutebrowser can use.

    Exceptions:
        KeyError:
            An unknown and required parameter is present in the URL. This
            usually means there's browser/addon specific functionality needed
            to build the URL (I'm looking at you and your browser, Google) that
            obviously won't be present here.
    """
    subst = {
        'searchTerms': '%s',  # for proper escaping later
        'language': '*',
        'inputEncoding': 'UTF-8',
        'outputEncoding': 'UTF-8'
    }

    # remove optional parameters (even those we don't support)
    for param in string.Formatter().parse(url):
        if param[1]:
            if param[1].endswith('?'):
                url = url.replace('{' + param[1] + '}', '')
            elif param[2] and param[2].endswith('?'):
                url = url.replace('{' + param[1] + ':' + param[2] + '}', '')
    return search_escape(url.format(**subst)).replace('%s', '{}') 
开发者ID:qutebrowser,项目名称:qutebrowser,代码行数:27,代码来源:importer.py

示例3: rm_pattern

# 需要导入模块: import string [as 别名]
# 或者: from string import Formatter [as 别名]
def rm_pattern(pattern):
    """Deletes all the files that match a formatting pattern."""
    # Build the args and kwargs to use '*' in the pattern
    args = list()
    kwargs = dict()
    for _, name, _, _ in string.Formatter().parse(pattern):
        if name is None:
            continue
        if name:
            kwargs[name] = '*'
        else:
            args.append('*')

    # Remove the corresponding files
    for f in glob.glob(pattern.format(*args, **kwargs)):
        os.remove(f)


# pylint: disable=too-many-instance-attributes 
开发者ID:AMOSSYS,项目名称:Fragscapy,代码行数:21,代码来源:tests.py

示例4: is_complex_format_str

# 需要导入模块: import string [as 别名]
# 或者: from string import Formatter [as 别名]
def is_complex_format_str(node):
    """Checks if node represents a string with complex formatting specs.

    Args:
        node (astroid.node_classes.NodeNG): AST node to check
    Returns:
        bool: True if inferred string uses complex formatting, False otherwise
    """
    inferred = utils.safe_infer(node)
    if inferred is None or not isinstance(inferred.value, six.string_types):
        return True
    try:
        parsed = list(string.Formatter().parse(inferred.value))
    except ValueError:
        # This format string is invalid
        return False
    for _, _, format_spec, _ in parsed:
        if format_spec:
            return True
    return False 
开发者ID:AtomLinter,项目名称:linter-pylama,代码行数:22,代码来源:logging.py

示例5: get_subdir_resolution

# 需要导入模块: import string [as 别名]
# 或者: from string import Formatter [as 别名]
def get_subdir_resolution(self):
        """Return the resolution for the subdir precision.

        Returns "year", "month", "day", or None (if there is no subdir).

        Based on parsing of self.subdir attribute.
        """
        fm = string.Formatter()
        fields = {f[1] for f in fm.parse(str(self.subdir))}
        if "day" in fields:
            return "day"
        if "month" in fields:
            if "doy" in fields:
                raise ValueError("Format string has both month and doy")
            return "month"
        if "year" in fields:
            if "doy" in fields:
                return "day"
            return "year" 
开发者ID:atmtools,项目名称:typhon,代码行数:21,代码来源:dataset.py

示例6: is_complex_format_str

# 需要导入模块: import string [as 别名]
# 或者: from string import Formatter [as 别名]
def is_complex_format_str(node):
    """Checks if node represents a string with complex formatting specs.

    Args:
        node (astroid.node_classes.NodeNG): AST node to check
    Returns:
        bool: True if inferred string uses complex formatting, False otherwise
    """
    inferred = utils.safe_infer(node)
    if inferred is None or not isinstance(inferred.value, str):
        return True
    try:
        parsed = list(string.Formatter().parse(inferred.value))
    except ValueError:
        # This format string is invalid
        return False
    for _, _, format_spec, _ in parsed:
        if format_spec:
            return True
    return False 
开发者ID:sofia-netsurv,项目名称:python-netsurv,代码行数:22,代码来源:logging.py

示例7: convert_field

# 需要导入模块: import string [as 别名]
# 或者: from string import Formatter [as 别名]
def convert_field(self, value, conversion):
        """
        Do conversion on the resulting object.

        supported conversions:
            'b': keep the parameter only if bool(value) is True.
            'v': keep both the parameter and its corresponding value,
                 the default mode.
        """
        if value[0] is self.sentinal:
            return string.Formatter.convert_field(self, value[1], conversion)
        if conversion is None:
            conversion = "v"
        if conversion == "v":
            return "" if value[1] is None else " ".join(value)
        if conversion == "b":
            return value[0] if bool(value[1]) else ""
        raise ValueError("Unknown conversion specifier {}".format(conversion)) 
开发者ID:avocado-framework,项目名称:avocado-vt,代码行数:20,代码来源:qemu_storage.py

示例8: format_field

# 需要导入模块: import string [as 别名]
# 或者: from string import Formatter [as 别名]
def format_field(self, value, format_spec):
            if hasattr(value, '__html_format__'):
                rv = value.__html_format__(format_spec)
            elif hasattr(value, '__html__'):
                if format_spec:
                    raise ValueError('No format specification allowed '
                                     'when formatting an object with '
                                     'its __html__ method.')
                rv = value.__html__()
            else:
                # We need to make sure the format spec is unicode here as
                # otherwise the wrong callback methods are invoked.  For
                # instance a byte string there would invoke __str__ and
                # not __unicode__.
                rv = string.Formatter.format_field(
                    self, value, text_type(format_spec))
            return text_type(self.escape(rv)) 
开发者ID:liantian-cn,项目名称:RSSNewsGAE,代码行数:19,代码来源:__init__.py

示例9: export_mpl_format_str_d3

# 需要导入模块: import string [as 别名]
# 或者: from string import Formatter [as 别名]
def export_mpl_format_str_d3(self, mpl_format_str):
        prefixes = []
        suffixes = []
        before_x = True
        format_spec_for_d3 = "" 
        for literal_text, field_name, format_spec, conversion in Formatter().parse(mpl_format_str): 
            if before_x:
                prefixes.append(literal_text)
            else:
                suffixes.append(literal_text)

            if field_name == "x" and format_spec and format_spec_for_d3 and self.is_output_d3:
                raise ValueError("D3 doesn't support multiple conversions")
                
            if field_name == "x":
                before_x = False
                format_spec_for_d3 = format_spec  

        prefix = "".join(prefixes)
        suffix = "".join(suffixes)
        return {
            "format_string": format_spec_for_d3,
            "prefix": prefix,
            "suffix": suffix
        } 
开发者ID:mpld3,项目名称:mplexporter,代码行数:27,代码来源:convertors.py

示例10: resolveTemplate

# 需要导入模块: import string [as 别名]
# 或者: from string import Formatter [as 别名]
def resolveTemplate(template, model, obj,mode='PUBLISH') :
    from rdf_io.models import getattr_path, ConfigVar
    vals = { 'model' : model }
    #import pdb; pdb.set_trace()
    for (literal,param,repval,conv) in Formatter().parse(template) :
        if param and param != 'model' :
            if( param[0] == '_' ) :
                val = ConfigVar.getval(param[1:],mode)
                if val:
                    vals[param] = val
                else:
                    #import pdb; pdb.set_trace()
                    raise Exception( "template references unset ConfigVariable %s" % param[1:])
            else:
                try:
                    vals[param] = urllib.quote_plus( str(iter(getattr_path(obj,param)).next()) )
                except:
                    if param == 'slug'  :
                        vals[param] = obj.id
    
    try:
        return template.format(**vals)
    except KeyError as e :
        raise KeyError( 'Property %s of model %s not found when creating API URL' % (e,model)) 
开发者ID:rob-metalinkage,项目名称:django-rdf-io,代码行数:26,代码来源:api.py

示例11: test_auto_numbering

# 需要导入模块: import string [as 别名]
# 或者: from string import Formatter [as 别名]
def test_auto_numbering(self):
        fmt = string.Formatter()
        self.assertEqual(fmt.format('foo{}{}', 'bar', 6),
                         'foo{}{}'.format('bar', 6))
        self.assertEqual(fmt.format('foo{1}{num}{1}', None, 'bar', num=6),
                         'foo{1}{num}{1}'.format(None, 'bar', num=6))
        self.assertEqual(fmt.format('{:^{}}', 'bar', 6),
                         '{:^{}}'.format('bar', 6))
        self.assertEqual(fmt.format('{:^{}} {}', 'bar', 6, 'X'),
                         '{:^{}} {}'.format('bar', 6, 'X'))
        self.assertEqual(fmt.format('{:^{pad}}{}', 'foo', 'bar', pad=6),
                         '{:^{pad}}{}'.format('foo', 'bar', pad=6))

        with self.assertRaises(ValueError):
            fmt.format('foo{1}{}', 'bar', 6)

        with self.assertRaises(ValueError):
            fmt.format('foo{}{1}', 'bar', 6) 
开发者ID:Microvellum,项目名称:Fluid-Designer,代码行数:20,代码来源:test_string.py

示例12: test_override_get_value

# 需要导入模块: import string [as 别名]
# 或者: from string import Formatter [as 别名]
def test_override_get_value(self):
        class NamespaceFormatter(string.Formatter):
            def __init__(self, namespace={}):
                string.Formatter.__init__(self)
                self.namespace = namespace

            def get_value(self, key, args, kwds):
                if isinstance(key, str):
                    try:
                        # Check explicitly passed arguments first
                        return kwds[key]
                    except KeyError:
                        return self.namespace[key]
                else:
                    string.Formatter.get_value(key, args, kwds)

        fmt = NamespaceFormatter({'greeting':'hello'})
        self.assertEqual(fmt.format("{greeting}, world!"), 'hello, world!') 
开发者ID:Microvellum,项目名称:Fluid-Designer,代码行数:20,代码来源:test_string.py

示例13: test_check_unused_args

# 需要导入模块: import string [as 别名]
# 或者: from string import Formatter [as 别名]
def test_check_unused_args(self):
        class CheckAllUsedFormatter(string.Formatter):
            def check_unused_args(self, used_args, args, kwargs):
                # Track which arguments actually got used
                unused_args = set(kwargs.keys())
                unused_args.update(range(0, len(args)))

                for arg in used_args:
                    unused_args.remove(arg)

                if unused_args:
                    raise ValueError("unused arguments")

        fmt = CheckAllUsedFormatter()
        self.assertEqual(fmt.format("{0}", 10), "10")
        self.assertEqual(fmt.format("{0}{i}", 10, i=100), "10100")
        self.assertEqual(fmt.format("{0}{i}{1}", 10, 20, i=100), "1010020")
        self.assertRaises(ValueError, fmt.format, "{0}{i}{1}", 10, 20, i=100, j=0)
        self.assertRaises(ValueError, fmt.format, "{0}", 10, 20)
        self.assertRaises(ValueError, fmt.format, "{0}", 10, 20, i=100)
        self.assertRaises(ValueError, fmt.format, "{i}", 10, 20, i=100) 
开发者ID:Microvellum,项目名称:Fluid-Designer,代码行数:23,代码来源:test_string.py

示例14: start

# 需要导入模块: import string [as 别名]
# 或者: from string import Formatter [as 别名]
def start(self):
        with(self._create_delete_lock):
            if (self.start_time is not None):
                return
            self._logger.debug("Starting Pipeline %s", self.identifier)
            self.request["models"] = self.models
            self._escape_source()
            self._ffmpeg_launch_string = string.Formatter().vformat(
                self.template, [], self.request)
            self._parse_ffmpeg_launch_string(self._ffmpeg_launch_string)
            self._set_properties()
            self._set_default_models()
            self._initialize_segment_recording()
            self._generate_ffmpeg_launch_args()
            self._unescape_source()
            thread = Thread(target=self._spawn, args=[self._ffmpeg_args])
            self.start_time = time.time()
            thread.start() 
开发者ID:intel,项目名称:video-analytics-serving,代码行数:20,代码来源:ffmpeg_pipeline.py

示例15: format_sql_in_function

# 需要导入模块: import string [as 别名]
# 或者: from string import Formatter [as 别名]
def format_sql_in_function(sql, into=None):
    kwargs = AnyArg({'USING': AnyUsingArg()})
    # TODO: Replace Formatter with sql.format(**kwargs) when dropping Python 2.
    sql = Formatter().vformat(sql, (), kwargs).replace("'", "''")
    using = kwargs.pop('USING')
    args = ', '.join([k for k in kwargs])
    if args:
        args = ', ' + args

    extra = ''
    if into is not None:
        extra += ' INTO ' + ', '.join(into)
    if using:
        extra += ' USING ' + ', '.join([a for a in using])

    return "EXECUTE format('%s'%s)%s;" % (sql, args, extra)


# TODO: Add `LIMIT 1` where appropriate to see if it optimises a bit. 
开发者ID:BertrandBordage,项目名称:django-tree,代码行数:21,代码来源:postgresql.py


注:本文中的string.Formatter方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。