【问题标题】:Inserting the same value multiple times when formatting a string格式化字符串时多次插入相同的值
【发布时间】:2010-11-16 13:45:57
【问题描述】:

我有一个这种形式的字符串

s='arbit'
string='%s hello world %s hello world %s' %(s,s,s)

字符串中的所有 %s 都具有相同的值(即 s)。 有没有更好的方法来写这个? (而不是列出 s 三次)

【问题讨论】:

  • 这个 % 字符串运算符将“在 Python 3.1 上被弃用并在稍后删除”docs.python.org/release/3.0.1/whatsnew/… 现在我想知道在版本兼容性和安全性方面最建议的方法是什么。
  • @Cawas 我知道这已经很晚了,但我喜欢使用str.format()。例如:query = "SELECT * FROM {named_arg}"; query.format(**kwargs),其中query 是格式字符串,kwargs 是一个字典,其键与格式字符串中的named_args 匹配。
  • @Cawas 是的,除了 Adam 使用元组表示法,其中 {0}{1}{2} 等对应于元组索引 012,分别。或者,也可以命名参数(如{named_arg})并在格式方法中设置每个参数,如下所示:'Hi {fname} {lname}!'.format(fname='John', lname='Doe')
  • @bignose 您已将两个问题标记为彼此重复,就像google.com/…

标签: python string format


【解决方案1】:
incoming = 'arbit'
result = '%(s)s hello world %(s)s hello world %(s)s' % {'s': incoming}

您可能希望阅读此内容以了解情况:String Formatting Operations

【讨论】:

  • 不错。已经忘记了这件事。 locals() 也可以。
  • @Goutham:如果您的 Python 版本是最新的,Adam Rosenfield 的答案可能会更好。
  • 确实如此。我还在适应新的字符串格式化操作。
  • 更好的是,您可以将基本字符串相乘:'%(s)s hello world '*3 % {'s': 'asdad'}
【解决方案2】:

您可以使用advanced string formatting,在 Python 2.6 和 Python 3.x 中可用:

incoming = 'arbit'
result = '{0} hello world {0} hello world {0}'.format(incoming)

【讨论】:

  • ~我的个人喜好,去kwargs风格result = '{st} hello world {st} hello world {st}'.format(st=incoming)
【解决方案3】:

可以使用字典类型的格式化:

s='arbit'
string='%(key)s hello world %(key)s hello world %(key)s' % {'key': s,}

【讨论】:

    【解决方案4】:

    取决于你所说的更好。如果您的目标是消除冗余,则此方法有效。

    s='foo'
    string='%s bar baz %s bar baz %s bar baz' % (3*(s,))
    

    【讨论】:

      【解决方案5】:
      >>> s1 ='arbit'
      >>> s2 = 'hello world '.join( [s]*3 )
      >>> print s2
      arbit hello world arbit hello world arbit
      

      【讨论】:

      • 我猜问题中的示例不是重复“hello world”,而是一个没有重复的真实模板。这就是我投反对票的原因。
      【解决方案6】:

      Fstrings

      如果您使用的是Python 3.6+,您可以使用新的f-strings,它代表格式化字符串,可以通过在字符串开头添加字符f 来将其标识为f-string.

      price = 123
      name = "Jerry"
      print(f"{name}!!, {price} is much, isn't {price} a lot? {name}!")
      >Jerry!!, 123 is much, isn't 123 a lot? Jerry!
      

      使用 f-strings 的主要好处是它们更具可读性、速度更快并提供更好的性能:

      适用于所有人的 Pandas 源代码:Python 数据分析,作者 Daniel Y. Chen

      基准测试

      毫无疑问,新的f-strings 更具可读性,因为您不必重新映射字符串,但正如上述引用所述,它是否更快?

      price = 123
      name = "Jerry"
      
      def new():
          x = f"{name}!!, {price} is much, isn't {price} a lot? {name}!"
      
      
      def old():
          x = "{1}!!, {0} is much, isn't {0} a lot? {1}!".format(price, name)
      
      import timeit
      print(timeit.timeit('new()', setup='from __main__ import new', number=10**7))
      print(timeit.timeit('old()', setup='from __main__ import old', number=10**7))
      > 3.8741058271543776  #new
      > 5.861819514350163   #old
      

      运行 1000 万次测试,似乎新的f-strings 在映射方面实际上更快。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2022-07-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-08-30
        • 2017-11-09
        • 2015-07-12
        相关资源
        最近更新 更多