【问题标题】:Looping through to a placeholder text block and joining each block of text循环到占位符文本块并加入每个文本块
【发布时间】:2019-09-09 22:45:05
【问题描述】:

我正在尝试使用 Python 从数组循环到带有占位符的文本块。但是我不知道如何在前一个文本块下附加或加入文本块。

如何将数组循环到带有占位符的文本块中,然后将各个文本块相互叠加输出。

我的数组看起来像:

[{'name': James, 'age': 40},{'name': Frank, 'age': 29}]

我的占位符模板:

f'''

Profile - 
Name: {name}
Age: {age}

'''

我正在尝试输出

Profile -
Name: James
Age: 40

Profile -
Name: Frank
Age: 28

我尝试过同时使用连接和连接 - 无济于事,即:

textBlock = ""
for i in data:

   text = f'''Name: {i{'name']}<br>Age: {i{'age']}<br>'''

   textBlock.join(text)

【问题讨论】:

    标签: python arrays python-3.x


    【解决方案1】:

    你的错误是这部分{i{'name']}应该是{i['name']}这里试试这个:

    data = [{'name': 'James', 'age': 40},{'name': 'Frank', 'age': 29}]
    
    result = '\n'.join(f'''Name: {i['name']}<br>Age: {i['age']}<br>''' for i in data)
    print(result)
    

    【讨论】:

      猜你喜欢
      • 2019-07-19
      • 2016-07-02
      • 1970-01-01
      • 1970-01-01
      • 2014-01-08
      • 1970-01-01
      • 2014-11-24
      • 2012-01-03
      • 1970-01-01
      相关资源
      最近更新 更多