Movatterモバイル変換


[0]ホーム

URL:


Open In App
Next Article:
Split String of list on K character in Python
Next article icon

We are given a string and our task is to split this string into a list of its individual characters, this can happen when we want to analyze or manipulate each character separately.For example, if we have a string like this: 'gfg' then the output will be ['g', 'f', 'g'].

Using List

The simplest way to convert a string into alist of characters in Python is to use the built-in list() function, which directly converts each character in the string to a list element.

Python
s="hello"a=list(s)print(a)

Output
['h', 'e', 'l', 'l', 'o']

Explanation:

  • list(s) splits the string into individual characters.
  • 'hello' becomes['h', 'e', 'l', 'l', 'o'].

Using List Comprehension

List comprehension provides a shorter and clearer syntax compared to the traditional loop approach.

Python
s="hello"a=[charforcharins]print(a)

Output
['h', 'e', 'l', 'l', 'o']

Explanation:

  • [char for char in s] iterates over each character ins.
  • char is added to the list for each iteration, producing the list of characters.

Using Unpacking Operator *

The unpacking operator * can be used to split a string into a list of characters in a single line. This approach is compact and works well for quickly converting a string to a list.

Python
s="hello"a=[*s]print(a)

Output
['h', 'e', 'l', 'l', 'o']

Explanation: [ *s ] unpacks each character in the strings into a list.

Using a Loop

We can also use a simple loop (for loop) to convert string into list of characters. This method is useful when we want to include additional logic within the loop.

Python
s="hello"a=[]forcharins:a.append(char)print(a)

Output
['h', 'e', 'l', 'l', 'o']

Explanation: This code splits the string s = "hello" into a list of characters by iterating through each character and appending it to the lista.

Related Articles:


Python Program to Split String into List of Characters

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