侯体宗的博客
  • 首页
  • Hyperf版
  • beego仿版
  • 人生(杂谈)
  • 技术
  • 关于我
  • 更多分类
    • 文件下载
    • 文字修仙
    • 中国象棋ai
    • 群聊
    • 九宫格抽奖
    • 拼图
    • 消消乐
    • 相册

在Python中字符串、列表、元组、字典之间的相互转换

Python  /  管理员 发布于 7年前   221

一、字符串(str)

字符串转换为列表

使用list()方法

str_1 = "1235"str_2 = 'zhangsan'str_3 = '''lisi'''tuple_1 = list(str_1)tuple_2 = list(str_2)tuple_3 = list(str_3)print(type(tuple_1))print(type(tuple_2))print(type(tuple_3))print(tuple_1)print(tuple_2)print(tuple_3)

运行结果:

使用Python中字符串的内置方法split()

Python split() 通过指定分隔符对字符串进行切片,如果参数 num 有指定值,则分隔 num+1 个子字符串
语法:str.split(str="", num=string.count(str)).
①str C 分隔符,默认为所有的空字符,包括空格、换行(\n)、制表符(\t)等。
②num C 分割次数。默认为 -1, 即分隔所有。

str_1 = "12 35 213"str_2 = 'zhang san shi a 'str_3 = 'zhang san shi a 'str_4 = '''li si wang wu'''list_1 = str_1.split(" ")list_2 = str_2.split(" ",1)list_3 = str_3.split(" ")list_4 = str_4.split(" ",2)print(type(list_1))print(type(list_2))print(type(list_3))print(type(list_4))print(list_1)print(list_2)print(list_3)print(list_4)

运行结果:

字符串 转换为 元组

使用tuple()方法

str_1 = "1235"str_2 = 'zhangsan'str_3 = '''lisi'''list_1 = tuple(str_1)list_2 = tuple(str_2)list_3 = tuple(str_3)print(type(list_1))print(type(list_2))print(type(list_3))print(list_1)print(list_2)print(list_3)

运行结果:

字符串 转换为 字典

利用eval()方法,可以将字典格式的字符串转换为字典

eval() 函数用来执行一个字符串表达式,并返回表达式的值。
语法:eval(expression[, globals[, locals]])
①expression C 表达式。
②globals C 变量作用域,全局命名空间,如果被提供,则必须是一个字典对象。③locals C 变量作用域,局部命名空间,如果被提供,可以是任何映射对象。

str_1 = "{'name':'zhangsan','age':14,'gender':'girl'}"dict_1 = eval(str_1)print(type(dict_1))print(dict_1)

运行结果:

利用json.loads()方法,可以将字典格式的字符串转换为字典

json.loads 用于解码 JSON 数据。该函数返回 Python 字段的数据类型。
语法:json.loads(s[, encoding[, cls[, object_hook[, parse_float[, parse_int[, parse_constant[, object_pairs_hook[, **kw]]]]]]]])

import jsonstr_1 = '{"name":"xiaoming","age":18}'dict_1 = json.loads(str_1)print(type(dict_1))print(dict_1)

运行结果:

二、列表(list)

列表转字符串

利用‘'.join()将列表中的内容拼接程一个字符串

Python join() 方法用于将序列中的元素(必须是str) 以指定的字符(''中指定的) 连接生成一个新的字符串。

list_1 = ['a', 'b', 'c']str_1 = ''.join(list_1)print(type(str_1))print(str_1)

运行结果:

列表转字典

利用for in rang将两个列表转换为字典

list_1 = ['a', 'b', 'c']list_2 = [1, 2, 3]dict_1 = {}for i in range(len(list_1)): dict_1[list_1[i]] = list_2[i]print(type(dict_1))print(dict_1)

运行结果:

利用python内置方法dict()和zip()将两个列表转换为字典

dict() 函数用于创建一个字典。
语法:class dict(**kwarg)
class dict(mapping, **kwarg)
class dict(iterable, kwarg)
①
kwargs C 关键字
②mapping C 元素的容器。
③iterable C 可迭代对象。

zip() 函数用于将可迭代的对象作为参数,将对象中对应的元素打包成一个个元组,然后返回由这些元组组成的列表。
语法:zip([iterable, …])
iterabl C 一个或多个迭代器;

list_1 = ['name', 'age']list_2 = ['zhangsan',18]dict_1 = dict(zip(list_1, list_2))print(type(dict_1))print(dict_1)

运行结果:

三、元组(tuple)

元组转换为字符串

  • 使用方法__str__
  • 返回一个对象的描述信息
tuple_1 = (1, 2, 3)str_1 = tuple_1.__str__()print(type(str_1))print(str_1)

运行结果:

元组转换为列表使用方法list()

list() 方法用于将元组转换为列表。
语法:list( tup )
tup C 要转换为列表的元组。

tuple_1 = (1, 2, 3)list_1 = list(tuple_1)print(type(list_1))print(list_1)

运行结果:

元组不能转换为字典

四、字典(dict)

字典转换为字符串

使用 json.dumps()方法

json.dumps 用于将 Python 对象编码成 JSON 字符串。
json.dumps(obj, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=None, indent=None, separators=None, encoding=“utf-8”, default=None, sort_keys=False, **kw)

字典转换为元组

  • 使用方法 tuple()
  • 字典在转换为元组之后,只会保存关键字
dict_1 = {"name":"zhangsan",   "age":18}tuple_1 = tuple(dict_1)print(type(tuple_1))print(tuple_1)

运行结果:

字典转换为列表

  • 使用方法 list()
  • 字典在转换为列表之后,只会保存关键字
dict_1 = {"name":"zhangsan",   "age":18}list_1 = list(dict_1)print(type(list_1))print(list_1)

运行结果:

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。


  • 上一条:
    Python获取统计自己的qq群成员信息的方法
    下一条:
    Python中BeautifuSoup库的用法使用详解
  • 昵称:

    邮箱:

    0条评论 (评论内容有缓存机制,请悉知!)
    最新最热
    • 分类目录
    • 人生(杂谈)
    • 技术
    • linux
    • Java
    • php
    • 框架(架构)
    • 前端
    • ThinkPHP
    • 数据库
    • 微信(小程序)
    • Laravel
    • Redis
    • Docker
    • Go
    • swoole
    • Windows
    • Python
    • 苹果(mac/ios)
    • 相关文章
    • 在python语言中Flask框架的学习及简单功能示例(0个评论)
    • 在Python语言中实现GUI全屏倒计时代码示例(0个评论)
    • Python + zipfile库实现zip文件解压自动化脚本示例(0个评论)
    • python爬虫BeautifulSoup快速抓取网站图片(1个评论)
    • vscode 配置 python3开发环境的方法(0个评论)
    • 近期文章
    • 智能合约Solidity学习CryptoZombie第三课:组建僵尸军队(高级Solidity理论)(0个评论)
    • 智能合约Solidity学习CryptoZombie第二课:让你的僵尸猎食(0个评论)
    • 智能合约Solidity学习CryptoZombie第一课:生成一只你的僵尸(0个评论)
    • 在go中实现一个常用的先进先出的缓存淘汰算法示例代码(0个评论)
    • 在go+gin中使用"github.com/skip2/go-qrcode"实现url转二维码功能(0个评论)
    • 在go语言中使用api.geonames.org接口实现根据国际邮政编码获取地址信息功能(1个评论)
    • 在go语言中使用github.com/signintech/gopdf实现生成pdf分页文件功能(0个评论)
    • gmail发邮件报错:534 5.7.9 Application-specific password required...解决方案(0个评论)
    • 欧盟关于强迫劳动的规定的官方举报渠道及官方举报网站(0个评论)
    • 在go语言中使用github.com/signintech/gopdf实现生成pdf文件功能(0个评论)
    • 近期评论
    • 122 在

      学历:一种延缓就业设计,生活需求下的权衡之选中评论 工作几年后,报名考研了,到现在还没认真学习备考,迷茫中。作为一名北漂互联网打工人..
    • 123 在

      Clash for Windows作者删库跑路了,github已404中评论 按理说只要你在国内,所有的流量进出都在监控范围内,不管你怎么隐藏也没用,想搞你分..
    • 原梓番博客 在

      在Laravel框架中使用模型Model分表最简单的方法中评论 好久好久都没看友情链接申请了,今天刚看,已经添加。..
    • 博主 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 @1111老铁这个不行了,可以看看近期评论的其他文章..
    • 1111 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 网站不能打开,博主百忙中能否发个APP下载链接,佛跳墙或极光..
    • 2016-10
    • 2016-11
    • 2018-04
    • 2020-03
    • 2020-04
    • 2020-05
    • 2020-06
    • 2022-01
    • 2023-07
    • 2023-10
    Top

    Copyright·© 2019 侯体宗版权所有· 粤ICP备20027696号 PHP交流群

    侯体宗的博客