Python字符串、元组、列表、字典互相转换的方法
作者:Ruthless 时间:2022-10-28 20:25:51
废话不多说了,直接给大家贴代码了,代码写的不好还去各位大侠见谅。
#-*-coding:utf-8-*-
#1、字典
dict = {'name': 'Zara', 'age': 7, 'class': 'First'}
#字典转为字符串,返回:<type 'str'> {'age': 7, 'name': 'Zara', 'class': 'First'}
print type(str(dict)), str(dict)
#字典可以转为元组,返回:('age', 'name', 'class')
print tuple(dict)
#字典可以转为元组,返回:(7, 'Zara', 'First')
print tuple(dict.values())
#字典转为列表,返回:['age', 'name', 'class']
print list(dict)
#字典转为列表
print dict.values
#2、元组
tup=(1, 2, 3, 4, 5)
#元组转为字符串,返回:(1, 2, 3, 4, 5)
print tup.__str__()
#元组转为列表,返回:[1, 2, 3, 4, 5]
print list(tup)
#元组不可以转为字典
#3、列表
nums=[1, 3, 5, 7, 8, 13, 20];
#列表转为字符串,返回:[1, 3, 5, 7, 8, 13, 20]
print str(nums)
#列表转为元组,返回:(1, 3, 5, 7, 8, 13, 20)
print tuple(nums)
#列表不可以转为字典
#4、字符串
#字符串转为元组,返回:(1, 2, 3)
print tuple(eval("(1,2,3)"))
#字符串转为列表,返回:[1, 2, 3]
print list(eval("(1,2,3)"))
#字符串转为字典,返回:<type 'dict'>
print type(eval("{'name':'ljq', 'age':24}"))
标签:python,元组,字典,字符串
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
解决pymysql cursor.fetchall() 获取不到数据的问题
2024-01-29 09:00:19
![](https://img.aspxhome.com/file/2023/0/94700_0s.jpg)
javascript this 关键字小提示
2009-02-03 13:22:00
Python操作Redis之设置key的过期时间实例代码
2022-02-11 06:13:05
Js-$.extend扩展方法使方法参数更灵活
2024-05-02 16:16:21
![](https://img.aspxhome.com/file/2023/8/132718_0s.gif)
Pandas 如何处理DataFrame中的inf值
2021-03-12 14:03:56
您需要了解的DIV+CSS网页布局的8条面试题目
2010-01-29 13:22:00
PHP字符串中提取文件名的实例方法
2023-06-12 18:57:32
基于python检查SSL证书到期情况代码实例
2023-06-26 06:23:58
python使用win32com在百度空间插入html元素示例
2021-09-13 17:00:13
PHP中过滤常用标签的正则表达式
2024-05-03 15:35:43
Python+Opencv答题卡识别用例详解
2021-09-08 22:16:13
![](https://img.aspxhome.com/file/2023/9/64619_0s.jpg)
keras.utils.to_categorical和one hot格式解析
2023-10-03 18:27:12
![](https://img.aspxhome.com/file/2023/8/133348_0s.jpg)
Vue便签的简单实现
2024-05-02 17:03:31
![](https://img.aspxhome.com/file/2023/3/130073_0s.png)
python 从远程服务器下载日志文件的程序
2021-03-06 01:39:15
为什么不压缩 HTML
2010-05-07 12:37:00
python 字符串详解
2022-09-27 04:44:25
![](https://img.aspxhome.com/file/2023/4/111854_0s.png)
PyQt5 closeEvent关闭事件退出提示框原理解析
2022-10-18 05:51:17
![](https://img.aspxhome.com/file/2023/1/92191_0s.png)
python实现搜索文本文件内容脚本
2022-01-30 18:51:22
![](https://img.aspxhome.com/file/2023/0/131350_0s.png)
Python操作dict时避免出现KeyError的几种解决方法
2022-12-30 14:48:26
Python pygame实现中国象棋单机版源码
2021-04-15 05:34:16
![](https://img.aspxhome.com/file/2023/5/115125_0s.png)