Converting Python Strings to Lists
Through some methods of strings, we can achieve mutual conversion between strings and lists.
Convert Python list to string
We can use the join() method of strings to join the elements in the list with the specified characters to generate a new string.
For example, if we want to convert the fruits list into a string, where each element is separated by a space, we can use the space as a string, and then call the join() method with the fruits list as an argument, and put the result Assigned to the variable strFruits. Then, we print out this string variable strFruits, the code is shown below.
>>> fruits=["apple","cherry","banana","orange","grape"] >>> strFruits=" ".join(fruits) >>> print(strFruits) apple cherry banana orange grape
Convert Python string to list
We can also split a string into a list using the specified delimiter using the split() method of the string.
Suppose we have a string strName that records the names of classmates, where each name is separated by a comma. We use the split() method to slice the string with the specified delimiter, and then use the split string list as the return value, assign it to the variable listName, and then print out the entire list. The code is as follows.
>>> strName="Zhu Xiaoyu, Li Xiaoxuan, Zhang Xiaorui, Li Xiaoyi" >>> listName=strName.split(",") >>> print(listName) ['Zhu Xiaoyu', 'Li Xiaoxuan', 'Zhang Xiaorui', ' Li Xiaoyi']