【Python基础数据】字符串str和列表list的相互转换,很实用

1.列表list转为字符串str

# _*_ coding: utf-8 _*_

# 使用join方法将列表数据连接成1个字符串,
# 可以通过符号连接,或为空
list = ["H","e","l","l","o",]
str1 = "".join(list)
str2 = ".".join(list)
str3 = " ".join(list)
print (str1)
print (str2)
print (str3)

'''运行结果:
Hello
H.e.l.l.o
H e l l o
'''

2.字符串str转为列表list

# _*_ coding: utf-8 _*_

# 通过split方法将字符串切片成列表格式
str1 = "Hello,I'm a Test Engineer."
list1 = str1.split()
print (list1)
'''运行结果:
["Hello,I'm", 'a', 'Test', 'Engineer.']
'''

# 通过点.进行切片
str1 = "www.csdn.net"
list1 = str1.split(".")
print (list1)
'''运行结果:
['www', 'csdn', 'net']
'''

# 直接通过list进行转换
str1 = "12345"
str2 = "Hello World!"
list1 = list(str1)
list2 = list(str2)
print (list1)
print (list2)

'''运行结果:
['1', '2', '3', '4', '5']
['H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd', '!']
'''
发布了63 篇原创文章 · 获赞 7 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/woshiyigerenlaide/article/details/104103792
今日推荐