【Python】字符串(str)与列表(list)的相互转换

1. str转list

# (1) list函数将字符串中每个字符转化为列表中的一个元素
str1 = 'Hello!'
list1 = list(str1)
print(list1)

# (2) split方法按指定字符块分隔原字符串,被分隔部分作为列表元素
str2 = 'Hello, 2020!'
list2 = list(str2.split(', '))
print(list2)

输出

['H', 'e', 'l', 'l', 'o', '!']
['Hello', '2020!']

 
2. list转str

# 使用join方法连接列表元素
list3 = ['H', 'e', 'l', 'l', 'o', '!']
str3 = ''.join(list3)  # 直接拼接列表中元素
str4 = '-'.join(list3)  # 使用'-'连接列表中元素
print(str3)
print(str4)

输出

Hello!
H-e-l-l-o-!

 
注意:对list直接使用str函数时,其作用是将该list的所有内容(包括列表的中括号和用于分隔元素的逗号+空格组合“, ”)转化为一个str,而不是将list中的元素连接为str。

list4 = [1, 2]
result = str(list4)  # 被转化为字符串"[1, 2]"
print(result)
print(type(result))

输出

[1, 2]
<class 'str'>

你可能感兴趣的:(Python,python,字符串,列表)