Using multiple arguments for string formatting in Python (e.g., '%s … %s')

后端 未结 8 2095
谎友^
谎友^ 2020-12-04 08:16

I have a string that looks like \'%s in %s\' and I want to know how to seperate the arguments so that they are two different %s. My mind coming from Java came u

相关标签:
8条回答
  • 2020-12-04 09:04

    Mark Cidade's answer is right - you need to supply a tuple.

    However from Python 2.6 onwards you can use format instead of %:

    '{0} in {1}'.format(unicode(self.author,'utf-8'),  unicode(self.publication,'utf-8'))
    

    Usage of % for formatting strings is no longer encouraged.

    This method of string formatting is the new standard in Python 3.0, and should be preferred to the % formatting described in String Formatting Operations in new code.

    0 讨论(0)
  • 2020-12-04 09:06

    On a tuple/mapping object for multiple argument format

    The following is excerpt from the documentation:

    Given format % values, % conversion specifications in format are replaced with zero or more elements of values. The effect is similar to the using sprintf() in the C language.

    If format requires a single argument, values may be a single non-tuple object. Otherwise, values must be a tuple with exactly the number of items specified by the format string, or a single mapping object (for example, a dictionary).

    References

    • docs.python.org/library/stdtypes - string formatting

    On str.format instead of %

    A newer alternative to % operator is to use str.format. Here's an excerpt from the documentation:

    str.format(*args, **kwargs)

    Perform a string formatting operation. The string on which this method is called can contain literal text or replacement fields delimited by braces {}. Each replacement field contains either the numeric index of a positional argument, or the name of a keyword argument. Returns a copy of the string where each replacement field is replaced with the string value of the corresponding argument.

    This method is the new standard in Python 3.0, and should be preferred to % formatting.

    References

    • docs.python.org/library/stdtypes - str.format - syntax

    Examples

    Here are some usage examples:

    >>> '%s for %s' % ("tit", "tat")
    tit for tat
    
    >>> '{} and {}'.format("chicken", "waffles")
    chicken and waffles
    
    >>> '%(last)s, %(first)s %(last)s' % {'first': "James", 'last': "Bond"}
    Bond, James Bond
    
    >>> '{last}, {first} {last}'.format(first="James", last="Bond")
    Bond, James Bond
    

    See also

    • docs.python.org/library/string - format examples
    0 讨论(0)
提交回复
热议问题