当前位置:网站首页>list and string conversion
list and string conversion
2022-08-09 07:05:00 【Anakin6174】
List and string are commonly used data types, and sometimes they need to be converted to each other;
A common operation:
ls3 = [3,47,5]st = str(ls3)print(st)new_list = list(st)print(type(new_list))print(new_list)#output""" [3, 47, 5] ['[', '3', ',', ' ', '4','7', ',', ' ', '5', ']'] """
It can be seen that it is easy to convert a list into a string. Conversely, parsing a string into a list is relatively troublesome, and the result of parsing is likely to be inconsistent with expectations;
Better way of handling:
1. List to string
Command: ''.join(list)
Among them, the quotation marks are the separators between characters, such as ",", ";", "\t", etc.
Such as:
list = [1, 2, 3, 4, 5]
''.join(list) The result is: 12345
','.join(list) The result is: 1,2,3,4,5
2. String to list
print list('12345')
Output: ['1', '2', '3', '4', '5']
print list(map(int, '12345'))
output: [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']
Reference: https://www.cnblogs.com/anningwang/p/7627117.html
边栏推荐
猜你喜欢
随机推荐
postgresql Window Functions
训练好的深度学习模型,多种部署方式
【模板】树链剖分 P3384
字节跳动面试题之镜像二叉树2020
tianqf的解题思路
SAP ALV data export many of the bugs
TCP段重组PDU
顺序表删除所有值为e的元素
redis学习笔记
SAP ALV 数据导出被截断的bug
sklearn数据预处理
先序遍历,中序遍历,后序遍历,层序遍历
Example of using the cut command
mysql summary
vlucas/phpdotenv phpdotenv获取变量内容偶尔出现返回false
半导体新能源智能装备整机软件系统方案设计
Singleton DCL (double check the lock) full han mode and the hungry
基于布朗运动的文本生成方法-LANGUAGE MODELING VIA STOCHASTIC PROCESSES
灵活好用的sql monitoring 脚本 part7
Integer 线程安全的