python's method of converting a list to a string

  • 2020-12-26 05:47:37
  • OfStack

The list is converted to a string

As shown below:


>>> list1=['ak','uk',4]
>>> list2=[str(i) for i in list1] # Use list derivation to convert all individual elements in a list to str type 
>>> list2 # View the transformed list 
['ak', 'uk', '4']
>>> list3=' '.join(list2) # Place the elements in the list in an empty string, separated by Spaces 
>>> list3 # Look at the resulting long string 
'ak uk 4'

The print method prints the elements in the string directly without displaying the format


>>> a=["1","2","3","4","5"] # All the elements in the list are str type 
>>> print(" ".join(a)) # Put the elements in the list in an empty string and print out the contents of the empty string 
1 2 3 4 5
>>> b=[1,2,3,4,5]
>>> c=map(str,b) # The elements in the list are not str The type needs to be put b The elements in the map into str type 
>>> type(b)
<class 'list'>
>>> type(c)
<class 'map'>
>>> print(" ".join(c)) # Why is it used here c Rather than b I don't know... 
1 2 3 4 5

How does the python string turn into a list

String is the most commonly used data type in Python. We can create strings using quotes (' or "). Creating a string is as simple as assigning a value to a variable. Sequences are the most basic data structure in Python. Each element in the sequence is assigned a number - its position, or index, the first index is 0, the second index is 1, and so on.

Python has six built-in types for sequences, but the most common are lists and tuples. The operations that a sequence can perform include indexing, slicing, adding, multiplying, and checking members.

In addition, Python has built-in methods for determining the length of a sequence and determining the largest and smallest elements. The list is the most commonly used Python data type and can appear as a comma-separated value within 1 square bracket. The data items in the list do not need to be of the same type. Create a list by enclosing the different data items separated by commas in square brackets.


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

The results are as follows:


['1', '2', '3', '4', '5']
['123', 'sjhid', 'dhi']
['www', 'google', 'com']

The Python strip() method is used to remove the character specified at the beginning and end of the string

split() is a list that splits a string into multiple strings


>>> image ='1.jsp,2.jsp,3.jsp,4.jsp'
>>> image_list = image.strip(',').split(',')
>>> print image_list
['1.jsp', '2.jsp', '3.jsp', '4.jsp']
>>>

Related articles: