Как получить массив из строки python

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.

Читайте также:  Java get query result

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']

Источник

3 способа преобразования строки в список в Python

Строка и список – одни из самых используемых типов данных в Python. Преобразование их из одного в другой является распространенной задачей в реальных проектах.

Что такое строка?

Строка – это массив байтов, представляющих символы Unicode. В Python нет встроенного символьного типа данных, но отдельный символ – это просто строка длиной 4 байт.

Что такое список?

В Python нет встроенного типа массива, но есть тип данных список. Списки могут помочь нам хранить несколько элементов в одной переменной.

Зачем преобразовывать строку в список в Python?

Преобразование из строки в список важно потому, что список может хранить несколько элементов в одной переменной, являясь изменяемым типом данных, в то время как строка неизменяема. Элементы списка упорядочены, могут изменяться и допускают дублирование значений. Реальный пример задачи по преобразования строки в список: получить список id участников мероприятия который мы получили с сайта в виде строки с id , разделенными запятой ( 134,256,321, 434). Если мы просто будем перебирать символы, то это не будет работать так, как нам это нужно.

Преобразование строки в список в Python

Чтобы преобразовать строку в список в Python, используйте метод string split() . Метод split() – это встроенный метод, который разделяет строки, сохраняет их в списке и возвращает список строк в исходной строке, используя “разделитель”.

Если разделитель не указан в аргументе функции или равен None, то применяется другой алгоритм разбиения: пробелы, идущие подряд, рассматриваются как единый разделитель.

Результат не будет содержать пустых строк в начале или конце, если в строке есть ведущий или завершающий пробел.

# app.py def stringToList(string): listRes = list(string.split(" ")) return listRes strA = "Millie Bobby Brown" print(stringToList(strA))

Посмотрите выходные данные.

➜ python3 app.py ['Millie', 'Bobby', 'Brown']

Вы можете проверить тип данных, используя функцию type().

# app.py def stringToList(string): listRes = list(string.split(" ")) return listRes strA = "Millie Bobby Brown" print(type(stringToList(strA)))

Преобразование строки в список с помощью методов strip() и split()

Метод strip() возвращает копию строки с удаленными начальными и конечными символами на основе переданного аргумента строки.

Метод strip() удаляет символы слева и справа в зависимости от аргумента.

# app.py initial_list = "[11, 21, 29, 46, 19]" print ("initial string", initial_list) print (type(initial_list)) op = initial_list.strip('][').split(', ') print ("final list", op) print (type(op))

➜ python3 app.py initial string [11, 21, 29, 46, 19] final list [’11’, ’21’, ’29’, ’46’, ’19’]

Здесь мы определили строку, которая выглядит как список.

Затем мы используем метод strip() и split() для преобразования строки в список, и, наконец, выводим список и его тип – для двойной проверки.

Преобразование с помощью модуля AST(Abstract Syntax Trees)

Модуль AST помогает приложениям Python обрабатывать деревья абстрактной синтаксической грамматики.

Абстрактный синтаксис может меняться с каждым выпуском Python; этот модуль помогает программно определить, как выглядит текущая грамматика.

У этого модуля есть замечательный метод ast.literal_eval(node_or_string ) . Метод позволяет извлечь из строки структуры, такие как строки, байты, числа, кортежи, списки, словари, множества, були и None .

# app.py import ast ini_list = "[11, 21, 19, 46, 29]" # выведем нужную нам строку и убедимся что это именно строка print("initial string", ini_list) print(type(ini_list)) # преобразуем строку в список res = ast.literal_eval(ini_list) # выведем результат print("final list", res) print(type(res))

➜ python3 app.py initial string [11, 21, 19, 46, 29] final list [11, 21, 19, 46, 29]

Преобразование строки в список с помощью метода json.loads()

Существует третий способ преобразования строки Python в список с помощью метода json.loads() .

# app.py import json # инициализируем строковое представление списка initial_list = "[11, 21, 19, 46, 29]" # выведем нужную нам строку и убедимся что это именно строка print("initial string", initial_list) print(type(initial_list)) # преобразуем строку в список op = json.loads(initial_list) # выведем результат print("final list", op) print(type(op))

➜ python3 app.py initial string [11, 21, 19, 46, 29] final list [11, 21, 19, 46, 29]

Сначала нам нужно импортировать модуль json , а затем использовать метод json.loads() для преобразования строки в формат списка. Будьте внимательны к тому как выглядит сам список. Json не сможет преобразовать обернутые в одинарные кавычки ‘ значения, так как данный формат предполагает использование двойных кавычек » , а значения вообще не обернутые в кавычки будут преобразованы к числам а не строкам.

Заключение

Преобразование строки в список в Python может быть выполнено несколькими способами. Самый простой способ – использовать метод split() . Метод split() разбивает строку на список, используя указанную строку-разделитель в качестве разделителя.

Источник

7 Powerful Ways To Convert String To List In Python

Convert string to list Python

In this article, we will be learning how to convert string to list in python. At first, we must understand the difference between the two. A string in Python can consist of only characters, whereas a list can consist of any data type. So, let us explore the 7 different ways to achieve this conversion.

Ways To Convert String To List In Python

1: Using string.split()

Syntax:

string.split(separator, maxsplit)

Parameters:

  • Separator: separator to use when splitting the string
    • Default value: whitespace

    Example:

    str1 = "Python pool for python knowledge" list1 = list(str1.split(" ")) print(list1)

    Output:

    ['Python', 'pool', 'for', 'python', 'knowledge']

    The split method by default takes whitespace as delimiter and separates the words of the string from by the whitespace and converts them into a list.

    2: Using list()

    To convert a string into list of characters, we can simply use type conversion using the inbuilt list() method.

    Syntax

    list(iterable)

    Parameter

    Example

    str1 = "Python pool for python knowledge" list1 = list(str1) print(list1)

    Output

    ['P', 'y', 't', 'h', 'o', 'n', ' ', 'p', 'o', 'o', 'l', ' ', 'f', 'o', 'r', ' ', 'p', 'y', 't', 'h', 'o', 'n', ' ', 'k', 'n', 'o', 'w', 'l', 'e', 'd', 'g', 'e']

    Using type conversion with the help of list() method, it directly converts the given string into a list of characters for us.

    3: Using list(map())

    Example

    str1 = "Python pool for python knowledge" str1=str1.split() list1=list(map(list,str1)) print(list1)

    Output

    [['P', 'y', 't', 'h', 'o', 'n'], ['p', 'o', 'o', 'l'], ['f', 'o', 'r'], ['p', 'y', 't', 'h', 'o', 'n'], ['k', 'n', 'o', 'w', 'l', 'e', 'd', 'g', 'e']]

    In this example, we have used both the split() method and the list() method to obtain the desired result. We first used the split() method to convert the string into a list of strings. We then applied the list() method to an individual element of the list to obtain the list of lists.

    4: Using list( map( int, list))

    Example

    str1="9 8 7 6 5 4 3 2 1" list1=list(str1.split()) list2=list(map(int,list1)) print(list2)

    Output

    In this code, we have first used the split() method to first convert the string into list. We then used type casting to convert the individual elements of the list into integer to get the list of integers as output.

    5: Using list( string.split() )

    Example

    str1 = "Python-pool-for-python-knowledge" list1 = list(str1.split("-")) print(list1)

    Output:

    ['Python', 'pool', 'for', 'python', 'knowledge']

    In this example, we have used a ‘ – ‘ to split our string and convert it into a list of strings. As the default value of split() is whitespace and in this example, we have used a custom separator ‘ – ‘ to split our string.

    6: Using json.loads()

    import json json_str = '' json_obj = json.loads(json_str) list1 = json_obj["str"] print(list1)

    Output:

    ['Python', 'pool', 'for', 'python', 'knowledge']

    At first, we have used json.loads() method to convert the JSON string into the dictionary. We then used the index of the dictionary to return the list stored at the index key .

    7: Using ast

    import ast str1 = "['Python', 'pool','for','python', 'knowledge']" print (type(str1)) print(str1) list1 = ast.literal_eval(str1) print (type(list1)) print (list1)

    Output:

     < class 'str' >[ 'Python' , 'pool' , 'for' , 'python' , 'knowledge' ] < class 'list' >[ 'Python' , 'pool' , 'for' , 'python' , 'knowledge' ]

    The ast.literal_eval() is used to evaluate a python expression.

    Convert String to List Python Dataframe

    .tolist() function will help to change a string present in the column to a list in Python data frame.

    Col = df.df_name.col_name.tolist() print(Col)

    Convert Multiline String to List Python

    To change a multiline string into a list we can use many functions like split(). It takes into account the newline characters. It also looks at the line breaks.

    def split_func(str): return s.split('\n') print("Before Splitting:") print("multiline\nstring.\n") print("After Splitting: ") print(split_func('multiline\nstring.\n'))

    FAQs

    You can change strings list to a list with float elements using typecasting.
    Its syntax is:
    print([float(no) for no in listA])
    With the help of list comprehension, we can optimize the code and change elements to float.

    To change a given string to a list with the string elements, use typecasting in Python.
    Example:
    code =[ “python” ]list(code)
    print(code)
    #this will give the given output: [‘python’]

    Conclusion

    With this, we come to the end of the article. These are the different ways of converting a string into a list. One can use any of the above methods as per their convenience and requirement.

    However, if you have any doubts or questions, do let me know in the comment section below. I will try to help you as soon as possible.

    Happy Pythoning!

    Источник

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