python将两个列表连接
时间: 2023-04-09 12:01:19 浏览: 60
可以使用extend()方法将两个列表连接起来,例如:
list1 = [1, 2, 3]
list2 = [4, 5, 6]
list1.extend(list2)
print(list1)
输出结果为:[1, 2, 3, 4, 5, 6]
相关问题
python 连接两个列表
你可以使用 Python 的 extend() 方法将两个列表连接起来。例如:
```
list1 = [1, 2, 3]
list2 = [4, 5, 6]
list1.extend(list2)
print(list1) # [1, 2, 3, 4, 5, 6]
```
你也可以使用加号(+)将两个列表相加,例如:
```
list1 = [1, 2, 3]
list2 = [4, 5, 6]
list3 = list1 + list2
print(list3) # [1, 2, 3, 4, 5, 6]
```
注意,使用 extend() 方法会直接在原来的列表上进行修改,而使用加号(+)则会生成一个新的列表。
python将两个字符串连接
可以使用"+"运算符将两个字符串连接起来,示例如下:
```python
str1 = "Hello"
str2 = "world"
result = str1 + str2
print(result) # 输出:Hello world
```
另外,也可以使用字符串的join()方法来连接多个字符串,示例如下:
```python
str_list = ["Hello", "world"]
result = " ".join(str_list)
print(result) # 输出:Hello world
```
其中,join()方法的参数是一个可迭代对象(如列表),它将可迭代对象中的所有字符串按照指定的分隔符连接起来。上述代码中,将列表中的两个字符串用空格连接起来。