用python创建一个列表 fruits = ["apple", "banana", "cherry", "date"],替换列表中的 "banana" 和 "cherry" 为 "blueberry" 和 "coconut"。打印修改后的列表。
时间: 2024-06-23 13:00:41 浏览: 188
要替换列表中的元素,你可以使用 Python 的 `list` 的 `index()` 方法找到元素的位置,然后用新的值替换。以下是代码示例:
```python
# 创建原始列表
fruits = ["apple", "banana", "cherry", "date"]
# 找到并替换 "banana"
index_banana = fruits.index("banana")
fruits[index_banana] = "blueberry"
# 找到并替换 "cherry"
index_cherry = fruits.index("cherry")
fruits[index_cherry] = "coconut"
# 打印修改后的列表
print("修改后的列表: ", fruits)
```
执行上述代码后,你会得到修改后的列表,其中 "banana" 和 "cherry" 都被替换为了 "blueberry" 和 "coconut"。
相关问题
将列表fruits=["apple", "orange", "grape"]中添加一个新元素"banana",执行语句为
你可以使用列表的append()方法将新元素添加到列表末尾,执行语句如下:
```python
fruits = ["apple", "orange", "grape"]
fruits.append("banana")
print(fruits) # 输出:['apple', 'orange', 'grape', 'banana']
```
fruits = { "apple", "banana", "orange" }; 字符串和
fruits = { "apple", "banana", "orange" }; 是一个字符串数组,它包含了三个元素:apple、banana和orange。字符串是一种常见的数据类型,用于表示文本信息。在这个例子中,fruits数组存储了三种水果的名称。
字符串是由字符组成的序列,可以使用引号(单引号或双引号)将字符括起来来创建字符串。在这个例子中,每个水果名称都被引号括起来,表示它们是字符串。
字符串可以用于各种操作,例如连接、比较、截取等。在编程中,字符串是非常常见和重要的数据类型之一。