【问题标题】:Most elegant way to format multi-line strings in Python在 Python 中格式化多行字符串的最优雅方式
【发布时间】:2014-02-18 20:06:15
【问题描述】:

我有一个多行字符串,我想用我自己的变量更改它的某些部分。我不太喜欢使用+ 运算符拼凑相同的文本。有没有更好的选择?

例如(需要内部引号):

line = """Hi my name is "{0}".
I am from "{1}".
You must be "{2}"."""

我希望能够多次使用它来形成一个更大的字符串,看起来像这样:

Hi my name is "Joan".
I am from "USA".
You must be "Victor".

Hi my name is "Victor".
I am from "Russia".
You must be "Joan".

有没有办法做类似的事情:

txt == ""
for ...:
    txt += line.format(name, country, otherName)

【问题讨论】:

    标签: python string coding-style formatting


    【解决方案1】:
    info = [['ian','NYC','dan'],['dan','NYC','ian']]
    >>> for each in info:
        line.format(*each)
    
    
    'Hi my name is "ian".\nI am from "NYC".\nYou must be "dan".'
    'Hi my name is "dan".\nI am from "NYC".\nYou must be "ian".'
    

    星号运算符会将列表解包到format 方法中。

    【讨论】:

      【解决方案2】:

      除了列表,您还可以使用字典。如果您要同时跟踪多个变量,这将非常有用。

      text = """\
      Hi my name is "{person_name}"
      I am from "{location}"
      You must be "{person_met}"\
      """
      person = {'person_name': 'Joan', 'location': 'USA', 'person_met': 'Victor'}
      
      print text.format(**person)
      

      注意,我输入的文本不同,因为它让我更容易排列文本。不过,您必须在开头“”和结尾“”之前添加一个“\”。

      现在,如果您的列表中有多个词典,您可以轻松完成

      people = [{'person_name': 'Joan', 'location': 'USA', 'person_met': 'Victor'},
                {'person_name': 'Victor', 'location': 'Russia', 'person_met': 'Joan'}]
      
      alltext = ""
      for person in people:
        alltext += text.format(**person)
      

      或使用列表推导

      alltext = [text.format(**person) for person in people]
      

      【讨论】:

        【解决方案3】:
        line = """Hi my name is "{0}".
        I am from "{1}".
        You must be "{2}"."""
        
        tus = (("Joan","USA","Victor"),
               ("Victor","Russia","Joan"))
        
        lf = line.format # <=== wit, direct access to the right method
        
        print '\n\n'.join(lf(*tu) for tu in tus)
        

        结果

        Hi my name is "Joan".
        I am from "USA".
        You must be "Victor".
        
        Hi my name is "Victor".
        I am from "Russia".
        You must be "Joan".
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2018-05-22
          • 2011-01-07
          • 2013-09-24
          • 1970-01-01
          • 1970-01-01
          • 2022-01-19
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多