Movatterモバイル変換


[0]ホーム

URL:


Open In App
Next Article:
Python - Converting list string to dictionary
Next article icon

Our task is to Convert string to a list in Python. Whether we need to break a string into characters or words, there are multiple efficient methods to achieve this. In this article, we'll explore these conversion techniques with simple examples. The most common way toconvert a string into a list is by using thesplit()method.

Using the split() Method

The split() method by defaultsplits a string based on spaces, but it can also split using a custom delimiter.

Python
s="Geeks for Geeks"a=s.split()print(a)

Output
['Geeks', 'for', 'Geeks']

Explanation:The split() method splits the string into words based on spaces.

Using list()

If we want to break down astring into list of individual charactersthen we can use list()function which is a simple and effective method. This approach adds each character of the string as an element in a list.

Python
s="Geeks for Geeks"a=list(s)print(a)

Output
['G', 'e', 'e', 'k', 's', ' ', 'f', 'o', 'r', ' ', 'G', 'e', 'e', 'k', 's']

Explanation:Thelist(s) function takes every character in the string "s" and places it as an element in the list.

Using list comprehension

List comprehension can be used for converting astring into list of individual characters. This approach is particularly useful if we want to manipulate each character before adding it to the list. While a loop can also achieve the same result but list comprehension provides better readability and conciseness.

Python
s="Geeks for Geeks"a=[chforchins]print(a)

Output
['G', 'e', 'e', 'k', 's', ' ', 'f', 'o', 'r', ' ', 'G', 'e', 'e', 'k', 's']

Explanation:[ch for ch in s] with this list comprehension we iterate over each character (ch) in the string "s" and add it to the list.

Related Articles:


Python | Program to convert String to a List

Similar Reads

We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood ourCookie Policy &Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences

[8]ページ先頭

©2009-2025 Movatter.jp