python - 在Python列表中使用同一个字符串两次

标签 python

我试图在以下列表中使用两个字符串,并希望使用一个字符串两次。我的意思是我不想在我的列表或元组中写两次同一个单词。

我的输出是 -

嗨,玛吉。 Maggie 我要去市场买铅笔和书。

嗨,露露。露露我要去市场买铅笔和书。

但我的错误是:元组索引超出范围 是否可以在我的元组中编写一次 maggie/lulu 并在两个地方使用它?

我的代码是:

first_tuple = ("magi","book","pencil")
second_tuple = ("lulu","copy","eraser")

together = (first_tuple, second_tuple)
New_List = list(together)


for i in range (len(New_List)):
    print ("Hi, {}. {} I will go to market to buy {} and {} .".format(*New_List[i]))

最佳答案

使用

print ("Hi, {0}. {0} I will go to market to buy {1} and {2} .".format(*New_List[i]))

大括号中的数字是格式参数列表的索引。请参阅the docs了解详情。

关于python - 在Python列表中使用同一个字符串两次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54283225/

相关文章:

python - 使用 Pattern.sub(r'\1' 时出现错误 "sre_constants.error: unmatched group"

python - 自动将 CSV 导入 Outlook 日历

python - 使用 Python 查询多个 Google Analytics ID

python - 是有多个脚本文件还是每个函数只有一个大脚本文件更好?

python - 将基类转换为派生类python(或扩展类的更多pythonic方式)

python - 如何使用日期时间在python中获取给定日期的下个月的同一天

python - SQLALCHEMY:当只知道 DSN 时如何连接到数据库?

python - 使用 setuptools 问题创建新的 virtualenv 1.11.5 失败

python - 我想将所有 .tgz 和 .tar 文件提取到一个目录中

python - 一次性运行操作应该放在Django框架的什么地方呢?