Как преобразовать строку в массив в Python — примеры
Python не имеет встроенного типа данных Array; вместо этого вы можете преобразовать строку Python в список. Таким образом, вы можете принять список Python в качестве массива.
Строка в массив
Чтобы преобразовать строку в массив в Python, используйте метод String.split(). Он отделяет строку от разделителя и возвращает элементы разделителя в виде отдельных элементов списка.
Метод Python String split() разбивает строку на список. Вы можете указать разделитель; разделителем по умолчанию является любой пробел.
How To Convert Python String To Array
This tutorial help to create python string to array. Python does not have an inbuilt array data type, it has a list data type that can be used as an array type. So basically, we are converting a string into a python list.
Python String to Array
We’ll convert String to array in Python. The python string package has split() method. The String.split() method splits the String from the delimiter and returns it as a list item. The split() method default separator is the whitespace but you can specify the separator.
Checkout other python string tutorials:
Syntax
- separator(optional) : It used to split the String.
- maxsplit(optional) : It specifies the number of splits to do. The default value is -1, which is “all occurrences”.
Example:
Output
[‘My’, ‘name’, ‘is’, ‘dominic’, ‘toretto’]
We have split string using white space delimiter. The splits() methods used to break the String based on that separator and return the list.
We can split the String at a specific character, use the Python split() function.
Example:
Output
[‘My’, ‘name’, ‘is’, ‘dominic’, ‘toretto’]
Python String to Array of Characters
Python String is a sequence of characters. We can convert it to the array of characters using the list() inbuilt function. When converting a string to an array of characters, whitespaces are also treated as characters.
Output:
[‘a’, ‘b’, ‘c’]
How to convert a string with comma-delimited items to a list in Python?
We can also convert a string into a comma-separated list, as like in other languages, we have an exploding method that ll break string using delimiter and convert into array.
Python string to array
In this article, we will discuss a string to be converted to an array in Python. In general, we know that an array is a data structure that has the capability of storing elements of the same data type in Python, whereas the list contains elements with different data type values. In this, we have to see how to convert a string to an array. We have to note that how we can split the given string into an array; it can be a set of characters or strings. This conversion can be done differently; the main technique is to use the split function to convert the string to an array.
Web development, programming languages, Software testing & others
How to convert a string to an array in python?
In this article, we are discussing on a string to an array. To do this, we are using the split() function for converting a string to an array. Now let us see below how to convert a single string to an array of characters, but we will use a simple function instead of the split() function in the below example.
Example #1
Code:
Output:
In the above program, we are splitting the given string into characters without using the split() function. In the above program, we can see we have created a function named “split_str” where we are passing a string, and it returns an array of characters. In the above screenshot, we can see the given string results into single characters.
Example #2
Now let us see how to use the split() function to split the string to array in the below example that is demonstrated as below:
Syntax:
Code:
Output:
In the above example, we can see we have the given string as “Educba Training,” which means there are two strings, and it is considered as a single string which is stored in the variable “t.” Then we have applied the split() function on the variable “t,” and the result is stored in another variable, “x.” Hence the output will be displayed as an array of strings such as “ [‘Educba,’ ‘Training’].”
Suppose if we have CSV strings, then also we can apply a split() function to these strings and obtain the array of strings, but we have to specify the separator of each string as “,.”
Example #3
Let us see an example below with CSV formatted string and converted to an array of strings using the same split() function.
Code:
Output:
In the above program, we can see str1 holds the CSV formatted string, which means comma-separated string, so to obtain the array of the string; first, we have to separate it from comma at each word or string in the given string. So when the split() function is applied on such string and we have specified (“,”) comma as delimiter or separator to obtain the array of string.
By default, when we specify or apply the split() function on any string, it will by default take “white space” as separator or delimiter. Hence if we have any string having any special characters and we want only to extract an array of strings, then we can just specify that special character as delimiter or separator to obtain the array of strings. We will see a simple example with some special characters in the given string. We need to obtain only the array of strings; then, we can do it again by applying the split() function with delimiter or separator special character in the given string.
Example #4
Code:
Output:
In the above program, we can see we have a given string with each string having special characters such as a hash (“#”) separated string. This string which is stored in the variable “str1” and split function applied on this string with separator or delimiter specified as (“ # ” ), and the result obtained is stored in another string str2. This string “str2” contains the array of strings separated by the special characters in the given string. Hence the result is as shown in the above screenshot, which has an array of strings from the given string having special characters.
Conclusion
In this article, we have seen what an array is and how to convert any string into an array. Firstly we have seen how to convert a given single string into characters by using the “for” loop. Then we have seen how to use the split() function to convert any string into an array of strings. First, we have seen how to use the split function on the string without specifying any separator or delimiter, then we have seen how to apply a split function on the CSV formatted string to obtain an array of string, and last we have also seen that this split() function can be used on any string having any kind of special characters in it to obtain the only array of strings.
Recommended Articles
This is a guide to Python string to an array. Here we discuss the introduction and examples to convert a string to an array along with code implementation. You may also have a look at the following articles to learn more –
Преобразование строки в список в Python: лучшие способы и практические примеры
В Python, строки могут быть преобразованы в списки различными способами. В этой статье мы рассмотрим наиболее распространенные методы преобразования строки в список, с примерами для каждого из них.
1. Метод split()
Один из наиболее распространенных способов преобразования строки в список — использовать метод split() . Этот метод разбивает строку на подстроки на основе указанного разделителя и возвращает список подстрок.
Вы также можете указать свой разделитель, передав его в качестве аргумента функции split() :
2. List Comprehension
Списковое включение — это компактный способ создания списков с использованием одной строки кода. Вы можете использовать списковое включение для преобразования строки в список символов.
3. Функция list()
Функция list() принимает итерируемый объект (например, строку) и преобразует его в список.
4. Метод splitlines()
Метод splitlines() разбивает строку на список строк, используя символы новой строки \n в качестве разделителей.
5. Регулярные выражения
Библиотека re предоставляет функции для работы с регулярными выражениями. Вы можете использовать функцию re.split() для разделения строки с использованием регулярного выражения в качестве разделителя.
6. Функция map()
Функция map() позволяет применять функцию к каждому элементу итерируемого объекта. Вы можете использовать map() в сочетании с split() для преобразования строки в список чисел.
Заключение
Мы рассмотрели различные способы преобразования строки в список в Python, включая использование метода split() , спискового включения, функции list() , метода splitlines() , регулярных выражений и функции map() . Эти методы предоставляют гибкость для выполнения преобразования, учитывая разные сценарии и требования к данным.
Подпишись на наш telegram-канал FullStacker
и получай свежие статьи, мануалы и шпаргалки по Python первым!