【问题标题】:How to add words/strings in lines from a list?如何从列表的行中添加单词/字符串?
【发布时间】:2023-01-09 18:34:27
【问题描述】:

output the Code

我正在尝试添加不同的词列表按顺序行。但是,我坚持下去。你能告诉我如何进行吗?我收到类型错误,无法获得输出。

我试图获得的输出:

it starts with: one or more.
it starts with: two or more.
it starts with: three or more.

我试过的代码:

a=["one","two","three"]

for i in a:
  print("it starts with: " + a[i] + "or more")

我得到的结果:

TypeError: list indices must be integers or slices, not str

【问题讨论】:

  • i 已经是值了。 for i in a: print("it starts with: " + i + " or more")

标签: python string list loops printing


【解决方案1】:

i已经是你要的元素了。

在 Python 中,表达式 for i in a 在循环的每次传递中将数组 a 的元素分配给变量 i。您不需要解决这些问题。

for i in a:
    print("it starts with: " + i + "or more")

【讨论】:

    【解决方案2】:

    所以你遇到的问题是,当你告诉 python 从列表中获取元素“i”时,“i”值不是索引而是值。所以基本上你的代码正在做的是一个 ["one"] ,它不起作用。 如果你用 i 替换 a[i] 它应该可以工作。此外,我建议将“+”替换为“,”,因为两个字符串和您从 a 中获取的值之间有一个空格。

    【讨论】:

      【解决方案3】:

      我已经代表列表中的每个元素。您可以使用 f-string 将其放入字符串中:

      for i in a:
          print(f"it starts with: {i} or more")
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-03-31
        • 1970-01-01
        • 2020-10-10
        • 2011-02-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多