Перевести строку в массив python

Python Program to convert String to a List

In this Python tutorial, we will understand how to convert Python String to List. Here we will see different methods to convert a given string to a list in Python.

We can use 8 methods in Python to convert a Python String to a list. These 8 methods are listed below.

  • Using list() function
  • Using map() function
  • Using lambda function
  • Using list comprehension
  • Using enumerate function
  • Using string slicing
  • Using split() method
  • Using re.findall() method

How to convert Python String to List

Here we will discuss all 8 different methods to convert the Python String to a list. Let us start with the first method of using a list() function in Python.

Method 1: Convert Python string to list using list()

In this method, we will simply use the list() function in python to convert the given string into a list.

Here is an example of this in Python.

# Defining a string country = 'United States' # Using list() to convert it list new_list = list(country) # Printing string print("String:", country) # Printing the list print("List:", new_list)

In the example, we defined a string variable named country storing a string value. Next, we utilized the list() function and passed the country variable as an argument to the list() function.

This will form a list with every single character as a separate list item.

Here is the result of the above Python program.

String: United States List: ['U', 'n', 'i', 't', 'e', 'd', ' ', 'S', 't', 'a', 't', 'e', 's']

Method 2: Convert Python string to list using map()

In this method, we will see how to use the map() function in Python to convert a string to a list.

Generally, we use the map() function in Python for applying a certain function on an iterable. So, here we will consider the string as an iterable and apply the str() function on each character of the string.

Also, we will use the list() function on the result to form a single list out of it.

Here is the code for this task in Python.

# Defining a string city_name = "Chicago" # Using map() to convert it list city_characters = list(map(str,city_name)) # Printing string print("String:", city_name) # Printing the list print("List:", city_characters)

The result of the above Python program is shown below.

String: Chicago List: ['C', 'h', 'i', 'c', 'a', 'g', 'o']

Method 3: Convert Python string to list using lambda and filter() function

Generally, the lambda function in Python is an anonymous function that we can define and call using a single line of code.

Читайте также:  Data structure and algorithm with javascript pdf

And in this method, we will use the lambda function in combination with the filter() function to convert a string to a list in Python.

# Defining a string city_name = "Houston" # Using lambda funtion to convert it list city_characters = list(filter(lambda char:(char in city_name),city_name)) # Printing string print("String:", city_name) # Printing the list print("List:", city_characters)

In the above code, we are using the filter() function and lambda function to define a filter condition. With this, we are getting each character from the string and then we are using the list() function to create a list out of it.

Here is the result of the above Python program.

String: Houston List: ['H', 'o', 'u', 's', 't', 'o', 'n']

Method 4: Convert Python string to list using list comprehension

Another quick way to convert a string to a list is by using list comprehension in Python.

Here we are using the for loop to iterate over each character from a given string and form a list using it.

Here is the sample code for this in Python.

# Defining a string city_name = "Phoenix" # Using list comprehension to convert it list city_characters = [ char for char in city_name ] # Printing string print("String:", city_name) # Printing the list print("List:", city_characters)

Once we execute the above Python program, we will get the following result where we will get a list of characters from the given string.

String: Phoenix List: ['P', 'h', 'o', 'e', 'n', 'i', 'x']

Method 5: Convert Python string to list using enumerate() function

The enumerate() is a built-in Python function that takes an iterable as input and returns a enumerate object that will add a counter to the iterable.

So, in this method, we will use the enumerate() function with the list comprehension to iterate over each string character and form a list using it.

Here is an example of this approach in Python.

# Defining a string city_name = "Houston" # Using enumerate() to convert it list city_characters = [ char for index, char in enumerate(city_name) ] # Printing string print("String:", city_name) # Printing the list print("List:", city_characters)

In the example, first, we defined a string named city_name and then we used the list comprehension with enumerate(). This will return a list in Python with each character as a separate list element.

Here is the result of the above Python program.

String: Houston List: ['H', 'o', 'u', 's', 't', 'o', 'n']

Method 6: Convert Python string to list using string slicing

String slicing in Python is another way to convert a given string to a list. In this method, first, we will define an empty list, then we will use slicing the given string to form a list.

Here is an example of this example in Python.

# Defining a string continent = "North America" # Defining a list char_list = [] # Using string slicing to convert to list char_list[:0] = continent # Printing string print("String:", continent) # Printing the list print("List:", char_list)

In the above example, we have defined a string variable named continent. After this, we used the concept of string slicing to convert the Python string to a list.

Читайте также:  Определить дату следующего дня питон

Also, once we execute the above Python program, we will get the following result.

String: North America List: ['N', 'o', 'r', 't', 'h', ' ', 'A', 'm', 'e', 'r', 'i', 'c', 'a']

Method 7: Convert Python string to list using the split() method

The split() method in Python is a built-in string method that is used to split a given string into a substring of the list based on a specified separator.

So, in this method, we will define a string and use the split() method on it to convert the string to a list in Python.

Here is an example of this task in Python.

# Defining a string info = "The United States is a federal republic consisting of 50 states" # Using split() to convert string to list char_list = info.split(" ") # Printing string print("String:", info) # Printing the list print("List:", char_list)

In the above example, we have defined a string named info. This info variable holds a string value related to the United States. Then we are simply using the split() method on the string to separate all the substrings based on empty space (” “).

In the last, we will get the following result in Python.

String: The United States is a federal republic consisting of 50 states List: ['The', 'United', 'States', 'is', 'a', 'federal', 'republic', 'consisting', 'of', '50', 'states']

Method 8: Convert Python string to list using re.findall() method

Another quick way to convert a string to a list is by using the re.findall() function in Python.

The re.findall() is a built-in function available in the re module of Python whose main role is to find all non-overlapping occurrences of a pattern in a string. And this function returns a list of all the non-overlapping occurrences.

Now, we can use this re.findall() function to find all string characters and form a list out of them.

Here is an example of this implementation in Python.

# Importing findall() from re import findall # Defining a string info = "The United States of America" # Using findall() to convert string to list char_list = findall('[a-zA-Z]', info) # Printing string print("String:", info) # Printing the list print("List:", char_list)

In the above example, we are using the re.findall() function to get a list of all the string characters that are there in the given string. In our case, the string is the info variable.

Here is the final result of the above Python program.

Python String to List

You may also like to read the following Python tutorials.

Conclusion

So, in this Python tutorial, we understood how to convert the Python string to list using 8 different methods. Moreover, for each method, we have given a detailed explanation and example.

Here is the list of 8 different methods that we covered in this tutorial.

  • Using list() function
  • Using map() function
  • Using lambda function
  • Using list comprehension
  • Using enumerate function
  • Using string slicing
  • Using split() method
  • Using re.findall() method

I am Bijay Kumar, a Microsoft MVP in SharePoint. Apart from SharePoint, I started working on Python, Machine learning, and artificial intelligence for the last 5 years. During this time I got expertise in various Python libraries also like Tkinter, Pandas, NumPy, Turtle, Django, Matplotlib, Tensorflow, Scipy, Scikit-Learn, etc… for various clients in the United States, Canada, the United Kingdom, Australia, New Zealand, etc. Check out my profile.

Читайте также:  Select database pdo php

Источник

How To Convert Python String To Array

In Python, we do not have an in-built array data type. However, we can convert Python string to list, which can be used as an array type.

Python String to Array

In the earlier tutorial, we learned how to convert list to string in Python. Here we will look at converting string to list with examples.

We will be using the String.split() method to convert string to array in Python.

Python’s split() method splits the string using a specified delimiter and returns it as a list item. The delimiter can be passed as an argument to the split() method. If we don’t give any delimiter, the default will be taken as whitespace.

split() Syntax

The Syntax of split() method is

string.split(separator, maxsplit)

split() Parameters

The split() method takes two parameters, and both are optional.

  • separator – The delimiter that is used to split the string. If not specified, the default would be whitespace.
  • maxsplit – The number of splits to be done on a string. If not specified, it defaults to -1, which is all occurrences.

Example 1: Split the string using the default arguments

In this example, we are not passing any arguments to the split() method. Hence it takes whitespace as a separator and splits the string into a list.

# Split the string using the default arguments text= "Welcome to Python Tutorials . " print(text.split())
['Welcome', 'to', 'Python', 'Tutorials', '. '] 

Example 2: Split the string using the specific character

In this example, we split the string using a specific character. We will be using a comma as a separator to split the string.

# Split the string using the separator text= "Orange,Apple,Grapes,WaterMelon,Kiwi" print(text.split(','))
['Orange', 'Apple', 'Grapes', 'WaterMelon', 'Kiwi']

Python String to Array of Characters

If you want to convert a string to an array of characters, you can use the list() method, an inbuilt function in Python.

Note: If the string contains whitespace, it will be treated as characters, and whitespace also will be converted to a list.

Example 1: String to array using list() method

# Split the string to array of characters text1= "ABCDEFGH" print(list(text1)) text2="A P P L E" print(list(text2))
['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H'] ['A', ' ', 'P', ' ', 'P', ' ', 'L', ' ', 'E']

You can also use list comprehension to split strings into an array of characters, as shown below.

Example 2: String to array using list comprehension

# Split the string to array of characters using list Comprehension text1= "ABCDEFGH" output1= [x for x in text1] print(output1) text2="A P P L E" output2=[x for x in text2] print(list(text2))
['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H'] ['A', ' ', 'P', ' ', 'P', ' ', 'L', ' ', 'E']

Источник

Оцените статью