【问题标题】:Python, replace a word in a string from a listPython,从列表中替换字符串中的单词
【发布时间】:2022-12-03 03:09:09
【问题描述】:

我有一个简单的字符串和一个列表:

string = "the secret key is A"
list = ["123","234","345"]

我需要替换一个项目(“A”),将该项目与列表中的另一个项目(“A123”)组合起来,次数与列表中的项目数一样多。基本上我想达到的结果是:

"the secret key is A123"
"the secret key is A234"
"the secret key is A345"

我知道我需要使用 for 循环,但我无法将这些项目连接在一起。

【问题讨论】:

  • 如果键在字符串的其他地方,输出会是什么?例如:"And the secret key is A"?

标签: python list replace


【解决方案1】:

请不要破坏保留关键字。

s = "the secret key is A"
lst = ["123","234","345"]

item = 'A'
newlst = [s.replace(item, f'{item}{tok}') for tok in lst]

>>> newlst
['the secret key is A123', 'the secret key is A234', 'the secret key is A345']

【讨论】:

  • 我在这里已经一年多了。以前当有人复制另一个人的答案时得到反对票但现在得到赞成票!
  • 你在说什么?抱歉,我之前没有看到您的回答。对我来说似乎也很好。
  • 我提前三分钟回答。我很难相信你没有看到我的回答,而且其他用户只给你点赞。 :)))(不同:你比我晚,你使用f-string
【解决方案2】:

您可以使用str.replace

st = "the secret key is A"

lst = ["123","234","345"]

key_rep = "A"

for l in lst:
    print(st.replace(key_rep, key_rep+l))

# Or as list_comprehension
# [st.replace(key_rep, key_rep+l) for l in lst]

输出:

the secret key is A123
the secret key is A234
the secret key is A345

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-04-01
    • 2012-11-26
    • 2013-03-17
    • 2012-09-14
    • 1970-01-01
    • 2015-07-03
    相关资源
    最近更新 更多