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

от admin

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

В этом посте мы обсудим, как преобразовать строку в список символов в Python.

Хотя Python позволяет вам получить доступ к отдельным символам строки с помощью оператора индекса [] а также позволяет легко перебирать строку, но в зависимости от вашего варианта использования вы можете создать список из символов строки. Это может быть достигнуто либо с помощью конструктора списка, либо с помощью понимания списка.

1. Использование list() конструктор

The list() конструктор строит список непосредственно из итерируемого объекта, а поскольку строка является итерируемой, вы можете создать из нее список. Выполнение list(s) на веревке s возвращает список всех символов, присутствующих в строке, в том же порядке, что и символы строки. Итак, все, что вам нужно сделать, это передать ваш строковый объект конструктору списка, как показано ниже:

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

Мы можем преобразовать строку в список в Python, используя функцию split().

Синтаксис функции split():

Давайте посмотрим на простой пример, в котором мы хотим преобразовать строку в список слов, то есть разделить ее разделителем на пробелы.

Если мы хотим разбить строку на список на основе пробелов, нам не нужно предоставлять какой-либо разделитель для функции split(). Кроме того, перед разделением строки на список слов удаляются любые начальные и конечные пробелы. Таким образом, результат останется таким же и для строки s = ‘Welcome To JournalDev’.

Давайте посмотрим на другой пример, где у нас есть данные CSV в строку, и мы преобразуем ее в список элементов.

Вывод: Список элементов в CSV = [‘Apple’, ‘Mango’, ‘Banana’].

Преобразование в список символов

Python String – это последовательность символов. Мы можем преобразовать его в список символов, используя встроенную функцию list(). При преобразовании строки в список символов пробелы также рассматриваются как символы. Кроме того, если есть начальные и конечные пробелы, они также являются частью элементов списка.

Если вы не хотите, чтобы начальные и конечные пробелы были частью списка, вы можете использовать функцию strip() перед преобразованием в список.

Python – Convert String to List

In Python, if you ever need to deal with codebases that perform various calls to other APIs, there may be situations where you may receive a string in a list-like format, but still not explicitly a list. In situations like these, you may want to convert the string into a list.

In this article, we will look at some ways of achieving the same on Python.

Converting List-type strings

A list-type string can be a string that has the opening and closing parenthesis as of a list and has comma-separated characters for the list elements. The only difference between that and a list is the opening and closing quotes, which signify that it is a string.

Let us look at how we can convert these types of strings to a list.

Method 1: Using the ast module

Python’s ast (Abstract Syntax Tree) module is a handy tool that can be used to deal with strings like this, dealing with the contents of the given string accordingly.

We can use ast.literal_eval() to evaluate the literal and convert it into a list.

Output

Method 2: Using the json module

Python’s json module also provides us with methods that can manipulate strings.

In particular, the json.loads() method is used to decode JSON-type strings and returns a list, which we can then use accordingly.

The output remains the same as before.

Method 3: Using str.replace() and str.split()

We can use Python’s in-built str.replace() method and manually iterate through the input string.

We can remove the opening and closing parenthesis while adding elements to our newly formed list using str.split(«,») , parsing the list-type string manually.

Output:

Converting Comma separated Strings

A comma-separated string is a string that has a sequence of characters, separated by a comma, and enclosed in Python’s string quotations.

To convert these types of strings to a list of elements, we have some other ways of performing the task.

Method 1: Using str.split(‘,’)

We can directly convert it into a list by separating out the commas using str.split(‘,’) .

Output:

Method 2: Using eval()

If the input string is trusted, we can spin up an interactive shell and directly evaluate the string using eval() .

However, this is NOT recommended, and should rather be avoided, due to security hazards of running potentially untrusted code.

Even so, if you still want to use this, go ahead. We warned you!

The output will be a list, since the string has been evaluated and a parenthesis has been inserted to now signify that it op is a list.

Читать:
Как поиграть в гран туризмо на пк

Output

This is quite long and is not recommended for parsing out comma-separated strings. Using str.split(‘,’) is the obvious choice in this case.

Conclusion

In this article, we learned some ways of converting a list into a string. We dealt with list-type strings and comma-separated strings and converted them into Python lists.

How to convert string representation of list to a list

I was wondering what the simplest way is to convert a string representation of a list like the following to a list :

Even in cases where the user puts spaces in between the commas, and spaces inside of the quotes, I need to handle that as well and convert it to:

I know I can strip spaces with strip() and split() and check for non-letter characters. But the code was getting very kludgy. Is there a quick function that I’m not aware of?

19 Answers 19

With ast.literal_eval you can safely evaluate an expression node or a string containing a Python literal or container display. The string or node provided may only consist of the following Python literal structures: strings, bytes, numbers, tuples, lists, dicts, booleans, and None .

The json module is a better solution whenever there is a stringified list of dictionaries. The json.loads(your_data) function can be used to convert it to a list.

The eval is dangerous — you shouldn’t execute user input.

If you have 2.6 or newer, use ast instead of eval:

Once you have that, strip the strings.

If you’re on an older version of Python, you can get very close to what you want with a simple regular expression:

This isn’t as good as the ast solution, for example it doesn’t correctly handle escaped quotes in strings. But it’s simple, doesn’t involve a dangerous eval, and might be good enough for your purpose if you’re on an older Python without ast.

There is a quick solution:

Unwanted whitespaces in the list elements may be removed in this way:

Alexei Sholik's user avatar

Inspired from some of the answers above that work with base Python packages I compared the performance of a few (using Python 3.7.3):

Method 1: ast

Method 2: json

Method 3: no import

I was disappointed to see what I considered the method with the worst readability was the method with the best performance. there are trade-offs to consider when going with the most readable option. for the type of workloads I use Python for I usually value readability over a slightly more performant option, but as usual it depends.

Peter Mortensen's user avatar

tosh's user avatar

If it’s only a one dimensional list, this can be done without importing anything:

ruohola's user avatar

You can do this

** best one is the accepted answer

Though this is not a safe way, the best answer is the accepted one. wasn’t aware of the eval danger when answer was posted.

David Beauchemin's user avatar

Tomato Master's user avatar

There isn’t any need to import anything or to evaluate. You can do this in one line for most basic use cases, including the one given in the original question.

One liner

Explanation

You can parse and clean up this list as needed using list comprehension.

Nested lists

If you have nested lists, it does get a bit more annoying. Without using regex (which would simplify the replace), and assuming you want to return a flattened list (and the zen of python says flat is better than nested):

If you need to retain the nested list it gets a bit uglier, but it can still be done just with regular expressions and list comprehension:

This last solution will work on any list stored as a string, nested or not.

Peter Mortensen's user avatar

Assuming that all your inputs are lists and that the double quotes in the input actually don’t matter, this can be done with a simple regexp replace. It is a bit perl-y, but it works like a charm. Note also that the output is now a list of Unicode strings, you didn’t specify that you needed that, but it seems to make sense given Unicode input.

The junkers variable contains a compiled regexp (for speed) of all characters we don’t want, using ] as a character required some backslash trickery. The re.sub replaces all these characters with nothing, and we split the resulting string at the commas.

Note that this also removes spaces from inside entries u'["oh no"]’ —> [u’ohno’]. If this is not what you wanted, the regexp needs to be souped up a bit.

Похожие статьи