String to list in python

String is an iterable object in python programming language. each letter of string can be accessing like list. In this post are provide all possible solution which is capable to convert a string to letter list or substrings list.

Convert string to list of character

There are many ways to convert string into character list. Such as using of type casting, using map function, using list comprehension and slicing so on. Here mentioning all the examples which are used to perform this task.

Example 1

By using of type casting by list method.

# Example 1
text = "Hello World"
result = list(text)
# Display result list
print(result)
['H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd']

Example 2

By using of map function.

# Example 2
text = "Hello World"
result = list(map(lambda ch: ch, text))
# Display result list
print(result)
['H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd']

Example 3

By using of using list comprehension.

# Example 3
text = "Hello World"
result = [letter for letter in text]
# Display result list
print(result)
['H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd']

Example 4

# Example 4
text = "Hello World"
result = list(text[:])
# Display result list
print(result)
['H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd']

Example 5

Python 3.5 and later.

# Example 6
text = "Hello World"
result = [*text]
# Display result list
print(result)
['H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd']

Converting a string into substring list

There are thousands of queries are possible to split a string into sublists by words. Here mentioning few of them which is generally used.

Example 1

Split string by whitespace.

# Example 1
text = "Hello World"
result = text.split()
# Display result list
print(result)
['Hello', 'World']

Example 2

Split string by comma.

# Example 2
text = "apple,mango,orange"
result = text.split(",")
# Display result list
print(result)
['apple', 'mango', 'orange']

Example 3

Substring list by selecting alternate characters from the string

# Example 3
text = "W-e-l-c-o-m-e- -b-a-c-k"
result = text[::2].split()
# Display result list
print(result)
['Welcome', 'back']



Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.

New Comment







© 2022, kalkicode.com, All rights reserved