当前位置:   article > 正文

Python字符串和列表相互转换_python 列表字符串转列表

python 列表字符串转列表

前言

字符串(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
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15

输出如下:

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

list to str

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

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

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

str6 = ", ".join(list3)
print(str6)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

输出如下:

wwwgooglecom
www.google.com
www, google, com
  • 1
  • 2
  • 3

补充

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
  • 2
  • 3
  • 4
  • 5
  • 6

输出如下:

1.jsp,2.jsp,3.jsp,4.jsp
['1.jsp', '2.jsp', '3.jsp', '4.jsp']
  • 1
  • 2
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/我家小花儿/article/detail/513549
推荐阅读
相关标签
  

闽ICP备14008679号