Python parsing string to list

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.

str_inp = '["Hello", "from", "AskPython"]'

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

Читайте также:  Html image with link tag

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.

import ast str_inp = '["Hello", "from", "AskPython"]' print(str_inp) op = ast.literal_eval(str_inp) print(op)
'["Hello", "from", "AskPython"]' ['Hello', 'from', 'AskPython']

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.

import json str_inp = '["Hello", "from", "AskPython"]' print(str_inp) op = json.loads(str_inp) print(op)

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.

str_inp = '["Hello", "from", "AskPython"]' str1 = str_inp.replace(']','').replace('[','') op = str1.replace('"','').split(",") print(op)

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.

str_inp = "Hello,from,AskPython'

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(‘,’) .

str_inp = "Hello,from,AskPython" op = str_inp.split(",") print(op)

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!

str_inp = "potentially,untrusted,code" # Convert to a quoted string so that # we can use eval() to convert it into # a normal string str_inp = "'" + str_inp + "'" str_eval = '' # Enclose every comma within single quotes # so that eval() can separate them for i in str_inp: if i == ',': i = "','" str_eval += i op = eval('[' + str_eval + ']') print(op)

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.

['potentially', 'untrusted', 'code']

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.

References

Источник

Parse String to List in Python

Parse String to List in Python

  1. Parse String to List With the str.split() Function in Python
  2. Parse String to List With the str.strip() Function in Python
  3. Parse String to List With the json.loads() Function in Python
  4. Parse String to List With the ast.literal_eval() Function in Python

In this tutorial, we are going to learn the methods to parse a string to a list in Python.

Parse String to List With the str.split() Function in Python

If in a scenario, we have a string representation of a list like ‘[ «A»,»B»,»C» , » D»]’ and want to convert that representation into an actual list of strings, we can use the str.split() function to split the string on the basis of each , . The str.split() function takes a delimiter/separator as an input parameter, splits the calling string based on the delimiter, and returns a list of substrings. The code sample below shows us how to parse a string representation of a list into an actual list with the str.split() function.

stringlist = '[ "A","B","C" , " D"]' print(stringlist.split(",")) 

We converted the stringlist string into a list by splitting it based on , with the stringlist.split(«,») function. As is apparent from the output, this approach has several problems and does not properly meet our requirements.

Parse String to List With the str.strip() Function in Python

To further convert a string like this into a list, we can use the str.strip() function. This str.strip() function also takes the delimiter/separator as an input parameter, strips the calling string based on the delimiter, and returns a list of much cleaner substrings. The sample code below shows us how to parse a string representation of a list into an actual list with the str.strip() function.

stringlist = '[ "A","B","C" , " D"]' print(stringlist.strip(",")) 

We converted the stringlist string into a list by splitting it on the basis of , with the stringlist.split(«,») function. We get a much cleaner list of strings this time around. The only disadvantage of this approach is that there are some unwanted blank spaces like the space in the fourth element of the list.

Parse String to List With the json.loads() Function in Python

We can also use the json module for our specific problem. The json.loads() function takes a JSON object as parameter, deserializes JSON object, and returns the results in a list. The JSON object parameter, in this case, can also be a string. The sample code below shows us how to parse a string representation of a list into an actual list with the json.loads() function.

import json stringlist = '[ "A","B","C" , " D"]' print(json.loads(stringlist)) 

We converted our stringlist string into a cleaner list with the json.loads(stringlist) function in Python. The only difference between the json.loads() function and our previous approaches is that we don’t have to specify any delimiter or separator character here. The json.loads() function automatically determines the delimiter for us. This method also contains the problem of unwanted blank spaces.

Parse String to List With the ast.literal_eval() Function in Python

One other method to solve our specific problem is the ast module. The ast.literal_eval() function takes a string representation of a Python literal structure like tuples, dictionaries, lists, and sets. If we pass the string into that literal structure, it returns the results. In our case, we have a string representation of a list. So, the ast.literal_eval() function takes this string, parses it into a list, and returns the results. The following code snippet shows us how to parse a string representation of a list into an actual list with the ast.literal_eval() function.

import ast stringlist = '[ "A","B","C" , " D"]' print(ast.literal_eval(stringlist)) 

We converted the stringlist string into a cleaner list with the ast.literal_eval() function in Python. Similar to the previous approach, we don’t have to specify a delimiter or a separator. Also similar to the previous approach, this method has the same problem of unwanted blank spaces. But these blank spaces can be easily removed.

Maisam is a highly skilled and motivated Data Scientist. He has over 4 years of experience with Python programming language. He loves solving complex problems and sharing his results on the internet.

Related Article — Python String

Related Article — Python List

Copyright © 2023. All right reserved

Источник

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!

    Источник

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