Как преобразовать строку в массив python

от admin

Python String to Array – How to Convert Text to a List

Dionysia Lemonaki

Dionysia Lemonaki

Python String to Array – How to Convert Text to a List

There will be times where you need to convert one data type to another.

Fear not, because Python offers a variety of different ways to help you do that.

In this article, you’ll see a few of the ways in which you can convert a string to a list.

Here is what we will cover:

What are Strings and Lists in Python?

A string is an ordered sequence of characters. It is a series of characters, with one character following the other.

A string is surrounded by either single or double quotation marks:

If you want to create a string that spans multiple lines, or what is known as a multiline string, use triple quotes to start and end it:

Strings are immutable. This means that once they have been created, they cannot change. The individal characters that make up a string cannot be altered.

For example, if you tried to change the first letter of a word from lowercase to uppercase, you would get an error in your code:

However, you can reassign a different string by updating the variable, like so:

A list is an ordered collection of data.

Multiple (typically related) items are stored together under the same variable.

You can create a list by enclosing zero or more items in square brackets, [] , each separated by a comma.

A list can contain any of Python’s built-in data types.

Lists are mutable.

You can change list items after the list has been created. This means that you can modify existing items, add new items, or delete items at any time during the life of the program.

How to Determine the Data Type of an Object in Python

To find the data type of an object in Python, use the built-in type() function, which has the following syntax:

The type() function will return the type of the object that was passed as an argument to the function.

This is commonly used for debugging purposes.

Let’s see how to use type() with strings and lists in the example below:

How to Convert a String to a List of Individual Characters

You can take a word and turn it into a list.

Every single character that makes up that word becomes an individual and separate element inside the list.

For example, let’s take the text «Python».

You can convert it to a list of characters, where each list item would be every character that makes up the string «Python».

This means that the P character would be one list item, the y character would be another list item, the t character would be another one, and so on.

The most straightforward way is to type cast the string into a list.

Tyepcasting means to directly convert from one data type to another – in this case from the string data type to the list data type.

You do this by using the built-in list() function and passing the given string as the argument to the function.

Let’s take a look at another example:

The text » Learning Python ! » has both leading and trailing whitespace, whitespace between the words «Learning» and «Python», and whitespace between the word «Python» and the exclamation mark.

When the string is converted to a list of characters, every whitespace is treated as an individual character and that’s why you see empty spaces, ‘ ‘ , as list items.

To remove whitespace only from the beginning and end of the string, use the strip() method.

To remove all and not just the leading and trailing whitespace and make it so no whitespace characters are included in the new list, use the replace() method instead:

How to Convert a String to a List of Words

Another way to convert a string to a list is by using the split() Python method.

The split() method splits a string into a list, where each list item is each word that makes up the string.

Each word will be an individual list item.

Syntax Breakdown of the split() Method in Python

The general syntax for the split() method is the following:

Let’s break it down:

  • string is the given string you want to turn into a list.
  • The split() method turns a string into a list. It takes two optional parameters.
  • separator is the first optional parameter, and it determines where the string will split. By default the separator is whitespace and the string will split wherever there is any whitespace.
  • maxsplit is the second optional parameter. It specifies the maximum number of splits to do. The default value, -1 , means that it splits across all the entire string and there are no limits to the splitting.

Let’s see an example of how that works.

In the above string, each word that makes up the string is separated by a whitespace.

To turn that string into a list of words, use the split() method.

You don’t need to specify a separator or a maxsplit paramter, as we want to separate all the words wherever there is whitespace between them.

The string was split based on where there was any whitespace, and each word that made up the string turned into an individual list item.

How to Use the split() method with a Separator

You can also convert a string to a list using a separator with the split() method. The separator can be any character you specify.

The string will separate based on the separator you provide.

For example, you can use a comma, , , as the separator.

The string will turn into a list whenever there is a comma, starting from the left.

Items that are comma separated will be the individual list items.

Let’s take the following string:

There is a comma that separates Hello world from I am learning Python! .

If we want to use that comma as a separator to create two individual list items, we would do the following:

Two separate items were created as list items and the separation occured where there was a comma.

Another example could be to separate a domain name, whenever there is a dot, . .

Every time there is a dot, a new list item will be added to the list.

How to Use the split() method with the maxsplit Paramter

As mentioned earlier, maxsplit is an optional parameter of the split() method.

It defines how many elements of the list will get split and turned into individual list items. By default, it is set to -1 , which means all elements that make up the string will be split.

But we can change the value to a specific number.

To split only two words and not every word, we set maxsplit to two:

maxsplit is set to 2 , which means a maximum of only two words will be split by space and will make two individual list items. The third list item will be the rest of the words that make up the initial string.

Using another example from the section above, you can combine a separator with maxsplit to make a targeted conversion of a string to a list:

In this example, the separator was a dot and only the first element got split.

How to Convert a String of Integers to a List of Integers

Numbers are considered strings when they are enclosed in either single or double quotes.

Say you have your date of birth stored as a string, like such:

To remove the slashes and store the numbers associated with the date, month, and year of birth as separate list items, you would do the following:

In the example, the separator was the slash, / , and whenever there was a slash a new list item was created.

If you take a closer look at the output you’ll see that the list items are still strings, since they are surrounded by single quotes and there has been no type conversion.

Читать:
Как добавить библиотеку в visual studio

To convert each list item from a string to an integer, use the map function.

The map function takes two arguments:

  • A function. In this case the function will be the int function.
  • An iterable, which is a sequence or collection of items. In this case the iterable is the list we created.

That is not exactly the output we wanted. When we check the data type, we see that we no longer have a list:

To correct this, we instead need to go back and add the list() function before the conversion:

Conclusion

And there you have it! You now know some of the ways to convert a string to a list in Python.

To learn more about the Python programming language, check out freeCodeCamp’s Scientific Computing with Python Certification.

You’ll start from the basics and learn in an interacitve and beginner-friendly way. You’ll also build five projects at the end to put into practice and help reinforce what you’ve learned.

How to convert a string with comma-delimited items to a list in Python?

Say the string is like text = «a,b,c» . After the conversion, text == [‘a’, ‘b’, ‘c’] and hopefully text[0] == ‘a’ , text[1] == ‘b’ ?

14 Answers 14

Just to add on to the existing answers: hopefully, you’ll encounter something more like this in the future:

But what you’re dealing with right now, go with @Cameron’s answer.

yurisich's user avatar

The following Python code will turn your string into a list of strings:

octopusgrabbus's user avatar

I don’t think you need to

In python you seldom need to convert a string to a list, because strings and lists are very similar

Changing the type

If you really have a string which should be a character array, do this:

Not changing the type

Note that Strings are very much like lists in python

Strings have accessors, like lists

Strings are iterable, like lists

Strings are lists. Almost.

firelynx's user avatar

In case you want to split by spaces, you can just use .split() :

vivek mishra's user avatar

If you actually want arrays:

If you do not need arrays, and only want to look by index at your characters, remember a string is an iterable, just like a list except the fact that it is immutable:

Ivan's user avatar

All answers are good, there is another way of doing, which is list comprehension, see the solution below.

for comma separated list do the following

Zeus's user avatar

the strip remove spaces around words.

To convert a string having the form a=»[[1, 3], [2, -6]]» I wrote yet not optimized code:

Unheilig's user avatar

split() is your friend here. I will cover a few aspects of split() that are not covered by other answers.

  • If no arguments are passed to split() , it would split the string based on whitespace characters (space, tab, and newline). Leading and trailing whitespace is ignored. Also, consecutive whitespaces are treated as a single delimiter.
  • When a single character delimiter is passed, split() behaves quite differently from its default behavior. In this case, leading/trailing delimiters are not ignored, repeating delimiters are not "coalesced" into one either.

So, if stripping of whitespaces is desired while splitting a string based on a non-whitespace delimiter, use this construct:

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

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.

Output

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.

Output

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

Output

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

Output

Ezoic

report this ad

How to Convert Python String to Array

To convert a string to an array in Python, you can use the string.split() function. For example, a string called str has a value “Kung Fu” that can be converted to an array using the str.split() method, which returns [“Kung”, “Fu”].

Syntax

Parameters

Both parameters are optional.

It takes a separator as an optional parameter used to split the String. By default, whitespace is a separator.

The maxsplit parameter specifies how many splits to do. The default value is -1, which is “all occurrences“.

Example

Output

In this example, we have not explicitly provided the separator, so it takes whitespace as a separator, splits the String based on that separator, and returns the list.

To split the String at a specific character, use the string.split() function and pass the specific character in the argument.

Output

You can specify the separator; the default separator is any whitespace.

How to convert a string to an array of characters

You can convert a string to an array of characters using Python’s built-in list() function. When converting a string to an array of characters, whitespaces are also treated as characters.

Output

In this example, split the String by converting the String to the list (using typecast).

FAQs

What is the difference between a string and an array in Python?

The main difference between a string and an array is that string is a sequence of characters, while an array is a data structure that holds a collection of elements of any data type in Python.

A string is immutable, and an array or list is a mutable data structure.

What are the ways to convert a string to an array in Python?

There are mainly three ways.

  1. Using the split() method.
  2. Using the list() method.
  3. Using the numpy.array() method.

Python does not have a built-in array data structure, but you can create an array using the numpy library’s np.array() function.

Can I convert a list of strings to an array of strings in Python?

Yes, use the np.array() function to convert a list of strings to an array.

Are there any limitations when converting strings to arrays in Python?

Depending on the method used to convert a string to an array and how the string is formatted, there may be limitations on the types of strings that can be converted or the desired output format.

Related Posts