当前位置:网站首页>list与string转换
list与string转换
2022-08-09 06:56:00 【Anakin6174】
list与string是常用的数据类型,有时候需要相互转换;
一个常见的操作:
ls3 = [3,47,5]
st = str(ls3)
print(st)
new_list = list(st)
print(type(new_list))
print(new_list)
#输出
""" [3, 47, 5] <class 'list'> ['[', '3', ',', ' ', '4', '7', ',', ' ', '5', ']'] """
可见,将list转成string很容易,反过来讲string解析成list就相对麻烦,很可能解析的结果与预期不一致;
比较好的处理方式:
1、list转字符串
命令:’’.join(list)
其中,引号中是字符之间的分割符,如“,”,“;”,“\t”等等
如:
list = [1, 2, 3, 4, 5]
‘’.join(list) 结果即为:12345
‘,’.join(list) 结果即为:1,2,3,4,5
2、字符串转list
print list(‘12345’)
输出: [‘1’, ‘2’, ‘3’, ‘4’, ‘5’]
print list(map(int, ‘12345’))
输出: [1, 2, 3, 4, 5]
str2 = “123 sjhid dhi”
list2 = str2.split() #or list2 = str2.split(" ")
print list2
[‘123’, ‘sjhid’, ‘dhi’]
str3 = “www.google.com”
list3 = str3.split(".")
print list3
[‘www’, ‘google’, ‘com’]
参考:https://www.cnblogs.com/anningwang/p/7627117.html
边栏推荐
猜你喜欢
longest substring without repeating characters
报错:FSADeprecationWarning: SQLALCHEMY_TRACK_MODIFICATIONS重大开销和将disab补充道
分布式理论
【报错】Root Cause com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure
线程的6种状态
高项 04 项目变更管理
(本章节完结)排序第五节——非比较排序(计数排序+基数排序+桶排序)(附有自己的视频讲解)
Error jinja2.exceptions.UndefinedError: 'form' is undefined
Quectel EC20 4G module dial related
力扣第 305 场周赛复盘
随机推荐
子路由及路由出口配置
字节跳动面试题之镜像二叉树2020
MySQL高级特性之分布式(XA)事务的介绍
按图搜索1688商品接口(item_search_img-按图搜索1688商品(拍立淘接口)代码对接教程
The JVM thread state
高项 04 项目整体管理
io.lettuce.core.RedisCommandTimeoutException Command timed out
codeforces Valera and Elections (这思维题是做不明白了)
物理层课后作业
当酷雷曼VR直播遇上视频号,会摩擦出怎样的火花?
leetcode 之盛水问题
P6 ali machine test of 2020 Fibonacci number
P7 Alibaba Interview Questions 2020.07 Sliding Window Algorithm (Alibaba Cloud Interview)
力扣 636. 函数的独占时间
线程池总结
Teach you how to make the Tanabata meteor shower in C language - elegant and timeless (detailed tutorial)
报错:flask: TypeError: ‘function‘ object is not iterable
C语言的内置宏(定义日志宏)
默默重新开始,第一页也是新的一页
先序遍历,中序遍历,后序遍历,层序遍历