惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

博客园 - 三生石上(FineUI控件)
博客园 - Franky
GbyAI
GbyAI
B
Blog
WordPress大学
WordPress大学
D
Docker
小众软件
小众软件
月光博客
月光博客
博客园 - 【当耐特】
T
The Blog of Author Tim Ferriss
IT之家
IT之家
腾讯CDC
Engineering at Meta
Engineering at Meta
Vercel News
Vercel News
H
Help Net Security
M
MIT News - Artificial intelligence
L
LangChain Blog
云风的 BLOG
云风的 BLOG
S
SegmentFault 最新的问题
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
美团技术团队
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
V
V2EX
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻

DigitalOcean Community Tutorials

Mastering grep with Regular Expressions for Efficient Text Search It's Time to Break Up with Your Cloud: Why AI Teams are Switching We Built a Private-Document AI App to Test Platform Security. Here Is What We Could Actually Verify. PostgreSQL Explained: A Complete Beginner-to-Advanced Guide How To Install and Configure Postfix on Ubuntu How To Build a Web Application Using Flask in Python 3 Build AI Reading List with DigitalOcean Functions and Mistral How To Concatenate Strings in Python How to Allow MySQL Remote Access Securely How To Install and Use Docker on Rocky Linux How To Build a Multi-Agent AI System with Docker Agent DSPy Use Cases: Build Optimized LLM Pipelines How To Submit AJAX Forms with jQuery Build an AI-Powered GPU Fleet Optimizer with the DigitalOcean AI Platform ADK Monitor GPU Utilization in Real Time: A Complete Guide Reduce File Size of Images in Linux - CLI and GUI methods Reduce PDF File Size in Linux: Tools and Methods How To Set Up a Private Docker Registry on Ubuntu How To Troubleshoot Terraform: Errors and Fixes How to Use Go Modules Python Multiprocessing Example: Process, Pool & Queue Convert Class Components to Functional Components with React Hooks How To Install and Configure Ansible on Ubuntu LLM Tokenizers Simplified: BPE, SentencePiece, and More How To Monitor System Authentication Logs on Ubuntu How to Use Traceroute and MTR to Diagnose Network Issues How to Deploy Postgres to Kubernetes Cluster Importing Packages in Go: A Complete Guide Create RAID Arrays with mdadm on Ubuntu How To Make an HTTP Server in Go
How To Convert a String to a List in Python
Pankaj Kumar · 2022-08-04 · via DigitalOcean Community Tutorials

Introduction

In Python, strings and lists are two fundamental data structures often used together in various applications. Converting a Python string to a list is a common operation that can be useful in many scenarios, such as data preprocessing, text analysis, and more.

This tutorial aims to provide a comprehensive guide on how to convert a string to a list in Python, covering multiple methods, their use cases, and performance considerations. By the end of this tutorial, you will have a solid understanding of how to effectively convert strings to lists in Python, enabling you to tackle a variety of tasks with confidence.

Key Takeaways

  • split() is the most common method for converting a delimited string to a list and handles leading and trailing whitespace automatically when called without arguments.
  • list() converts a string into a list of individual characters, including spaces and special characters.
  • json.loads() is the correct method for parsing JSON-encoded strings into Python lists or dictionaries.
  • re.split() handles strings with inconsistent or multiple delimiters using a regular expression pattern.
  • List comprehension gives you per-character control and can be combined with conditions to filter characters during conversion.
  • Always choose the method that matches your input format: delimited text, raw characters, or structured JSON data.

Python Convert String to List

Let’s look at a simple example where we want to convert a string to list of words i.e. split it with the separator as white spaces.

s = 'Welcome To DigitalOcean'
print(f'List of Words ={s.split()}')

Output: List of Words =['Welcome', 'To', 'DigitalOcean']

If you are not familiar with f-prefixed string formatting, please read f-strings in Python

If we want to split a string to list based on whitespaces, then we don’t need to provide any separator to the split() function. Also, any leading and trailing whitespaces are trimmed before the string is split into a list of words. So the output will remain same for string s = ' Welcome To DigitalOcean ' too. Let’s look at another example where we have CSV data into a string and we will convert it to the list of items.

s = 'Apple,Mango,Banana'
print(f'List of Items in CSV ={s.split(",")}')

Output: List of Items in CSV =['Apple', 'Mango', 'Banana']

Python String to List of Characters

Python String is a sequence of characters. We can convert it to the list of characters using list() built-in function. When converting a string to 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.

s = 'abc$ # 321 '

print(f'List of Characters ={list(s)}')

Output: List of Characters =['a', 'b', 'c', '$', ' ', '#', ' ', '3', '2', '1', ' '] If you don’t want the leading and trailing whitespaces to be part of the list, you can use strip() function before converting to the list.

s = ' abc '

print(f'List of Characters ={list(s.strip())}')

Output: List of Characters =['a', 'b', 'c'] That’s all for converting a string to list in Python programming.

Different Methods for Converting a String to a List

1. Using split()

The split() method is the most common way to convert a string into a list by breaking it at a specified delimiter.

string = "apple,banana,cherry"
list_of_fruits = string.split(",")
print(list_of_fruits)  # Output: ['apple', 'banana', 'cherry']

2. Using List Comprehension

If you need more control over how elements are added to the list, list comprehension is a powerful option.

string = "hello"
list_of_chars = [char for char in string]
print(list_of_chars)  # Output: ['h', 'e', 'l', 'l', 'o']

3. Using json.loads() for Structured Data

For parsing JSON-encoded strings, json.loads() is the preferred method.

import json
string = '["apple", "banana", "cherry"]'
list_of_fruits = json.loads(string)
print(list_of_fruits)  # Output: ['apple', 'banana', 'cherry']

Comparison of Methods

Method Use Case Performance
split() Simple delimited strings Fast
List Comprehension Character-by-character conversion Moderate
json.loads() Parsing structured data Depends on size

Handling Inconsistent Delimiters

If delimiters vary, use regular expressions with re.split().

import re
string = "apple,banana;cherry"
list_of_fruits = re.split(r'[;,]', string)
print(list_of_fruits)  # Output: ['apple', 'banana', 'cherry']

Converting Nested Data Structures

Convert JSON-like strings to nested lists.

import json
string = '{"apple": ["red", "green"], "banana": ["yellow", "green"]}'
nested_list = json.loads(string)
print(nested_list)  # Output: {'apple': ['red', 'green'], 'banana': ['yellow', 'green']}

Performance Benchmarks

Measure the efficiency of different methods with large datasets.

import time

# Method 1: split()
start_time = time.time()
for _ in range(1000000):
    string = "apple,banana,cherry"
    list_of_fruits = string.split(",")
end_time = time.time()
print(f"Time taken for split(): {end_time - start_time} seconds")

# Method 2: List Comprehension
start_time = time.time()
for _ in range(1000000):
    string = "hello"
    list_of_chars = [char for char in string]
end_time = time.time()
print(f"Time taken for List Comprehension: {end_time - start_time} seconds")

# Method 3: json.loads()
import json
start_time = time.time()
for _ in range(1000000):
    string = '["apple", "banana", "cherry"]'
    list_of_fruits = json.loads(string)
end_time = time.time()
print(f"Time taken for json.loads(): {end_time - start_time} seconds")

FAQs

1. Can we convert a string to a list in Python?

Yes, you can convert a string to a list using methods like split(), list comprehension, or json.loads(). For example, using split():

string = "apple,banana,cherry"
list_of_fruits = string.split(",")
print(list_of_fruits)  # Output: ['apple', 'banana', 'cherry']

2. How to convert a string back to a list?

You can use .split() for delimited strings or json.loads() for structured data. For example, using json.loads():

import json
string = '["apple", "banana", "cherry"]'
list_of_fruits = json.loads(string)
print(list_of_fruits)  # Output: ['apple', 'banana', 'cherry']

3. What is list() in Python?

The list() function is a built-in Python function that converts an iterable (like a string, tuple, or set) into a list. This is particularly useful when you need to manipulate individual elements of an iterable or when you want to convert a string into a list of characters. For example, list("hello") would return ['h', 'e', 'l', 'l', 'o'].

4. How do you convert a string into a list in Python without split()?

You can use list comprehension or list(string) for character-by-character conversion. For example, using list comprehension:

string = "hello"
list_of_chars = [char for char in string]
print(list_of_chars)  # Output: ['h', 'e', 'l', 'l', 'o']

5. What is the difference between split() and list() in Python?

split() divides a string by a delimiter, while list() converts each string character into a separate list element. For example:

# Using split()
string = "apple,banana,cherry"
list_of_fruits = string.split(",")
print(list_of_fruits)  # Output: ['apple', 'banana', 'cherry']

# Using list()
string = "hello"
list_of_chars = list(string)
print(list_of_chars)  # Output: ['h', 'e', 'l', 'l', 'o']

6. How do you handle nested data in a string while converting to a list?

Use json.loads() to parse structured JSON data into nested lists. Here’s an example:

import json
string = '{"apple": ["red", "green"], "banana": ["yellow", "green"]}'
nested_list = json.loads(string)
print(nested_list)  # Output: {'apple': ['red', 'green'], 'banana': ['yellow', 'green']}

Conclusion

In this tutorial, you covered five methods for converting a string to a list in Python: split() for delimited strings, list() for character-by-character conversion, json.loads() for structured data, re.split() for inconsistent delimiters, and list comprehension for fine-grained control. You also saw how method choice affects performance across large datasets.

The right method depends on your input format. For most everyday tasks, split() is the starting point. For JSON data, json.loads() is the only correct choice. For anything more complex, re.split() or list comprehension gives you the control you need.

To go further with Python strings and lists:

Creative CommonsThis work is licensed under a Creative Commons Attribution-NonCommercial- ShareAlike 4.0 International License.