前言

字符串(str)和列表(list)相互转换,这个需求时有发生。举一个例子,在做算法题时,若输入为数字和逗号组合的字符串,我们在编写算法时则需要将字符串中的数字存入列表中。下面介绍字符串和列表相互转换的方法。

str to list

split("str")可以将一个字符串分隔成多个字符串组成的列表,以函数中的字符或字符串作为分隔标准。以下为代码示例:

str1 = "12345"
list1 = list(str1)
print(list1)

str2 = "123 sjhid dhi"
list2 = str2.split()  # or list2 = str2.split(' ')
print(list2)

str3 = "www.google.com"
list3 = str3.split('.')
print(list3)

str4 = "12||34||56||78"
list4 = str4.split("||")
print(list4)

输出如下:

['1', '2', '3', '4', '5']
['123', 'sjhid', 'dhi']
['www', 'google', 'com']
['12', '34', '56', '78']

list to str

join()可以将列表结合字符或字符串组成字符串,代码示例如下:

str4 = ''.join(list3)
print(str4)

str5 = '.'.join(list3)
print(str5)

str6 = ", ".join(list3)
print(str6)

输出如下:

wwwgooglecom
www.google.com
www, google, com

补充

strip()方法用于移除字符串头尾指定的字符,代码示例如下:

image = ",1.jsp,2.jsp,3.jsp,4.jsp,,"
# imageList = image.strip(',').split(',')
imageStrip = image.strip(',')  # 移除字符串首尾的逗号
print(imageStrip)
imageList = imageStrip.split(',')
print(imageList)

输出如下:

1.jsp,2.jsp,3.jsp,4.jsp
['1.jsp', '2.jsp', '3.jsp', '4.jsp']
Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐