3. 将字符串s = "alex"转换成列表与元组 s = "alex" 将列表与元组进行相互转换
时间: 2023-05-28 11:03:30 浏览: 151
将字符串s = "alex"转换成列表:
```python
s = "alex"
lst = list(s)
print(lst) # ['a', 'l', 'e', 'x']
```
将字符串s = "alex"转换成元组:
```python
s = "alex"
tup = tuple(s)
print(tup) # ('a', 'l', 'e', 'x')
```
将列表转换成元组:
```python
lst = ['a', 'l', 'e', 'x']
tup = tuple(lst)
print(tup) # ('a', 'l', 'e', 'x')
```
将元组转换成列表:
```python
tup = ('a', 'l', 'e', 'x')
lst = list(tup)
print(lst) # ['a', 'l', 'e', 'x']
```
相关问题
tuple函数可以将列表或字符串转化为元组嘛
是的,`tuple()`函数可以将列表或字符串转化为元组。在Python中,元组是一种不可变序列,用圆括号 `()` 表示。`tuple()` 函数可以将其他可迭代对象(例如列表、字符串等)转换为元组。下面是一些示例代码:
```python
# 将列表转换为元组
my_list = [1, 2, 3]
my_tuple = tuple(my_list)
print(my_tuple) # 输出:(1, 2, 3)
# 将字符串转换为元组
my_string = "Hello, World!"
my_tuple = tuple(my_string)
print(my_tuple) # 输出:('H', 'e', 'l', 'l', 'o', ',', ' ', 'W', 'o', 'r', 'l', 'd', '!')
```
需要注意的是,元组是不可变的,因此不能对元组中的元素进行修改,添加或删除。
python 将列表中的字符元素转换为元组
A:可以使用Python列表的内置函数map()和tuple()来将列表中的字符元素转换为元组。例如,假设我们有以下列表:
```python
my_list = ['apple', 'banana', 'cherry']
```
我们可以使用以下代码将其转换为元组:
```python
my_tuple = tuple(map(str, my_list))
```
这将使用map()函数将列表中的字符元素转换为字符串,并使用tuple()函数将结果转换为元组。现在,my_tuple将包含('apple', 'banana', 'cherry')。