python在列表中的某个字符串前添加字符
时间: 2023-10-15 07:03:54 浏览: 166
你可以使用列表推导式或循环来在列表中的某个字符串前添加字符。以下是使用循环实现的示例代码:
```python
my_list = ["apple", "banana", "orange"]
target_string = "banana"
prefix = "fruit_"
for i in range(len(my_list)):
if my_list[i] == target_string:
my_list[i] = prefix + my_list[i]
print(my_list)
```
输出结果为:`['apple', 'fruit_banana', 'orange']`
这段代码首先定义了一个列表 `my_list`,以及要添加的前缀字符串 `prefix` 和目标字符串 `target_string`。然后使用 `for` 循环遍历列表,当找到目标字符串时,在该字符串前添加前缀,并将修改后的字符串赋值回列表中。最后输出修改后的列表。
另外,如果你想使用列表推导式实现,可以这样写:
```python
my_list = ["apple", "banana", "orange"]
target_string = "banana"
prefix = "fruit_"
my_list = [prefix + s if s == target_string else s for s in my_list]
print(my_list)
```
输出结果与上面的代码相同。该代码使用了列表推导式,将原列表中的每个元素进行判断,如果该元素为目标字符串,则在其前面添加前缀。
阅读全文
相关推荐
















