【问题标题】:appending a string to a list of strings if the string in the list is equal to some variable in python如果列表中的字符串等于python中的某个变量,则将字符串附加到字符串列表
【发布时间】:2021-11-20 13:46:24
【问题描述】:
a=['item1', 'item2', 'item3', ...]
b='item2'

现在,如果我想说在列表 'a' 中的 'item2' 的开头和结尾添加 *,我该怎么做?

【问题讨论】:

  • (1) 在列表中找到'item2'的索引; (2) 将'*item2*' 分配给该索引

标签: python-3.x list


【解决方案1】:

您可以使用 list comprehension

>>> a = ['item1', 'item2', 'item3']
>>> b = 'item2'
>>> c = [f'*{s}*' if s == b else s for s in a]
>>> c
['item1', '*item2*', 'item3']

【讨论】:

    猜你喜欢
    • 2018-09-13
    • 2011-01-04
    • 2012-09-14
    • 1970-01-01
    • 2012-12-05
    • 1970-01-01
    • 2020-06-20
    • 2021-04-25
    • 1970-01-01
    相关资源
    最近更新 更多