How to convert a list into a string and vice versus in Python

String and lists are the data structures commonly used in various programming languages for multiple purposes. We often see exchangeable conversions between list and string, for example, storing data into the Redis cache hash, retrieving them back, and tokenizing them into elements. In this post, we are learning how to convert a list into a string and vice versa with Python language.

Convert a string into a list

Using the split() method on a string variable

If we have a string variable/object, using the split() method of string object is straightforward. The method accepts two optional arguments: a separator and a maxsplit.

  • The separator is a string, default separator is any whitespace.
  • The maxsplit specifies how many splits to do. The default value is -1, which is “all occurrences”.

Note: When maxsplit is specified, the list will contain the specified number of elements plus one.

Let’s look at the snippet below.

organism = "104341|Postia placenta|https://identifiers.org/taxonomy/104341"
parts = organism.split("|")
if parts is not None:
   accession = parts[0]
   name = parts[1]
   uri = parts[2]

The split() method will trunk the organism string into smaller elements based on the “|” character as the separator.

Using the list() built-in function

A string is considered a sequence of characters. We can convert it to a list of characters using the list() built-in function. When converting a string to a list of characters, whitespaces are also treated as characters. Also, if there are leading and trailing whitespaces, they are part of the list elements too. Therefore, it is recommended to remove the leading and trailing whitespace before applying the list() function using the strip() method.

with open("all-names.dat", "r", endcoding="utf-8") as file:
    names = file.readlines()
    names = [name.strip() for name in names]
    for name in names:
        length = len(list(name))
        print("{} has {} characters.".format(name, length))

The snippet above will compute the length of the names saved in a file.

The list() method is particularly useful when you need to perform operations on each character of a string, such as counting occurrences of characters, replacing characters, or any other form of character-level manipulation. It provides a straightforward way to break down a string into its constituent characters for individual processing.

If the string contains Python expressions or literals, for example, a string of Python arrays such as ["9606", "Homo sapiens", "https://identifiers.org/taxonomy:9606"].  To manipulate such data, we can use the json.loads or ast.literal_eval method.

Using the json.load() or ast.literal_eval()

As these methods are deliberately implemented for special data,  a string representing a JSON array or containing Python literals can be directly converted into a Python list using these methods. Using the json.loads() method for string-to-list conversion is particularly effective when dealing with data received from web APIs or stored in files in JSON format. It allows for the straightforward transformation of JSON array strings into Python lists, enabling further data manipulation and processing in Python. The ast.literal_eval() method, found in the ast module (Abstract Syntax Trees), is designed to parse strings containing Python literals and safely evaluate them. This method is particularly useful for converting strings that look like Python lists, dictionaries, tuples, and other native data types into their actual Python representations.

import ast, json

curators = '["Lucian Smith", "Tung Nguyen", "Rahuman Sheriff"]'
lst_curators = json.loads(curators)
print(curators)

# using literal_eval
lst = ast.literal_eval(curators)
print(lst)

Both methods give the same result.

Now, let’s work out how to convert a list to a string.

Convert a list into a string

Using the join() method on a string variable

The join() method is the built-in str.join() function of str. The method returns a string which is the concatenation of the strings in an iterable such as list. Let’s take a look at the example below.

// names include the family, middle names and the given name
names = ["Nguyen", "Vu Ngoc", "Tung"]
full_name = " ".join(names)
print(full_name) // Nguyen Vu Ngoc Tung

Using a traditional loop over every element of the list

The example below clearly gives us how to obtain the same result with a traditional loop (for or while). The aim is to combine all items from the publication to produce a string presenting all information of the publication.

publication = ["PubMed", "2383232", "Common Features in lncRNA Annotation and Classification: A Survey", "2021 Dec 13;7(4):77", "Noncoding RNA"]
s = ""
for item in publication:
   s += item + "\t"
print(s)

Conclusion

We have gone through some effective ways to convert a list into a string and vice versus. Converting a string to a list in Python can be accomplished through various methods, each suited to different scenarios and data formats. These methods are commonly used in our projects so we cannot ignore them. Understanding these methods enhances your data manipulation capabilities, allowing you to handle and process strings in Python with greater flexibility and efficiency.

We hope that you find the post useful. Feel free to give your thoughts in the comment box below.

References

[1] Built-in Types, https://docs.python.org/3/library/stdtypes.html, accessed on 24, Dec 2024.

[2] How to concatenate (join) items in a list to a single string, https://stackoverflow.com/questions/12453580/how-to-concatenate-join-items-in-a-list-to-a-single-string, accessed on 17, Dec 2023