【问题标题】:Output formatting in Python: replacing several %s with the same variablePython 中的输出格式:用相同的变量替换几个 %s
【发布时间】:2011-08-08 13:36:50
【问题描述】:

我正在尝试维护/更新/重写/修复一些看起来有点像这样的 Python:

variable = """My name is %s and it has been %s since I was born.
              My parents decided to call me %s because they thought %s was a nice name.
              %s is the same as %s.""" % (name, name, name, name, name, name)

脚本中到处都是这样的小sn-ps,我想知道是否有更简单(更Pythonic?)的方式来编写这段代码。我发现了一个这样的例子,它把同一个变量替换了大约 30 次,感觉很丑。

解决(在我看来)丑陋的唯一方法是把它分成很多小块吗?

variable = """My name is %s and it has been %s since I was born.""" % (name, name)
variable += """My parents decided to call me %s because they thought %s was a nice name.""" % (name, name)
variable += """%s is the same as %s.""" % (name, name)

【问题讨论】:

    标签: string-formatting python


    【解决方案1】:

    改用字典。

    var = '%(foo)s %(foo)s %(foo)s' % { 'foo': 'look_at_me_three_times' }
    

    format 带有明确的编号。

    var = '{0} {0} {0}'.format('look_at_meeee')
    

    好吧,或者format 带有命名参数。

    var = '{foo} {foo} {foo}'.format(foo = 'python you so crazy')
    

    【讨论】:

    • 您的最后一个选项读起来很漂亮,非常感谢 - 正是我对 Python 的期望!
    【解决方案2】:

    使用格式化字符串:

    >>> variable = """My name is {name} and it has been {name} since..."""
    >>> n = "alex"
    >>>
    >>> variable.format(name=n)
    'My name is alex and it has been alex since...'
    

    {} 中的文本可以是描述符或索引值。

    另一个花哨的技巧是使用字典结合**运算符来定义多个变量。

    >>> values = {"name": "alex", "color": "red"}
    >>> """My name is {name} and my favorite color is {color}""".format(**values)
    'My name is alex and my favorite color is red'
    >>>
    

    【讨论】:

    • 正是我想要的。干净简单。 +1
    【解决方案3】:

    Python 3.6 引入了一种更简单的字符串格式化方法。您可以在PEP 498获取有关它的详细信息

    >>> name = "Sam"
    >>> age = 30
    >>> f"Hello, {name}. You are {age}."
    'Hello, Sam. You are 30.'
    

    它还支持运行时评估

    >>>f"{2 * 30}"
    '60'
    

    它也支持字典操作

    >>> comedian = {'name': 'Tom', 'age': 30}
    >>> f"The comedian is {comedian['name']}, aged {comedian['age']}."
     The comedian is Tom, aged 30.
    

    【讨论】:

      【解决方案4】:

      使用新的string.format

      name = 'Alex'
      variable = """My name is {0} and it has been {0} since I was born.
                My parents decided to call me {0} because they thought {0} was a nice name.
                {0} is the same as {0}.""".format(name)
      

      【讨论】:

        【解决方案5】:
        >>> "%(name)s %(name)s hello!" % dict(name='foo')
        'foo foo hello!'
        

        【讨论】:

          【解决方案6】:

          您可以使用命名参数。 See examples here

          【讨论】:

            【解决方案7】:
            variable = """My name is {0} and it has been {0} since I was born.
                          My parents decided to call me {0} because they thought {0} was a nice name.
                          {0} is the same as {0}.""".format(name)
            

            【讨论】:

              【解决方案8】:

              【讨论】:

                【解决方案9】:

                如果您使用的是 Python 3,那么您也可以利用 f-strings

                myname = "Test"
                sample_string = "Hi my name is {name}".format(name=myname)
                

                sample_string = f"Hi my name is {myname}"
                

                【讨论】:

                  猜你喜欢
                  • 1970-01-01
                  • 1970-01-01
                  • 2021-09-12
                  • 2015-01-25
                  • 2022-11-02
                  • 1970-01-01
                  • 2022-11-03
                  • 1970-01-01
                  • 1970-01-01
                  相关资源
                  最近更新 更多