当前位置:网站首页>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

原网站

版权声明
本文为[Anakin6174]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/221/202208090655473654.html