Open In App

Python – Breaking Up String Variables

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Share
Report issue
Report

Prerequisite: itertools

Given a String, the task is to write a Python program to break up the string and create individual elements.

Input : GeeksForGeeks
Output : [ ‘G’, ‘e’, ‘e’, ‘k’, ‘s’, ‘F’, ‘o’, ‘r’, ‘G’, ‘e’, ‘e’, ‘k’, ‘s’ ]
 

Input: Computer
Output: [ ‘C’, ‘o’, ‘m’, ‘p’, ‘u’, ‘t’, ‘e’, ‘r’]

Below are some ways to do the above task.

Method #1: Using join() function

The join() method provides a flexible way to create strings from iterable objects. It joins each element of an iterable (such as list, string, and tuple) by a string separator (the string on which the join() method is called) and returns the concatenated string.

Python3




a = "GeeksForGeeks"
 
split_string = list(''.join(a))
 
print(split_string)


Output:

[‘G’, ‘e’, ‘e’, ‘k’, ‘s’, ‘F’, ‘o’, ‘r’, ‘G’, ‘e’, ‘e’, ‘k’, ‘s’]

Time Complexity: O(n2) -> (join+conversion to list)

Space Complexity: O(n)

Method #2: Using for loop

Python3




a = "GeeksForGeeks"
 
res = [i for ele in a for i in ele]
 
print(res)


Output:

[‘G’, ‘e’, ‘e’, ‘k’, ‘s’, ‘F’, ‘o’, ‘r’, ‘G’, ‘e’, ‘e’, ‘k’, ‘s’]

Time Complexity: O(n2)

Space Complexity: O(n)

Method #3: Using chain.from_iterable()

Python3




from itertools import chain
 
 
a = "GeeksForGeeks"
 
# using chain.from_iterable()
# to convert list of string and characters
# to list of characters
res = list(chain.from_iterable(a))
 
# printing result
print(str(res))


Output:

[‘G’, ‘e’, ‘e’, ‘k’, ‘s’, ‘F’, ‘o’, ‘r’, ‘G’, ‘e’, ‘e’, ‘k’, ‘s’]

Time Complexity: O(n2) -> (chain+converting to list)

Space Complexity: O(n)

Method #5: Using map() function

Here is the step-by-step algorithm for the given code:

Define a string variable “a” and initialize it with the value “GeeksForGeeks”.
Define a lambda function that takes a character as an input and returns that character.
Use the map() function to apply the lambda function to each character in the string.
Store the result in a list named “result”.
Print the list “result”.

Python3




a = "GeeksForGeeks"
 
result = list(map(lambda x: x, a))
 
print(result)


Output

['G', 'e', 'e', 'k', 's', 'F', 'o', 'r', 'G', 'e', 'e', 'k', 's']

Time complexity:
The time complexity of the map() function is O(n), where n is the length of the input string. In this case, the map() function is applied to each character in the string, so the time complexity of the code is O(n).

Space complexity:
The space complexity of the code is O(n), where n is the length of the input string. The map() function creates a new list of characters that is the same length as the input string, so the space complexity of the code is O(n).



Last Updated : 25 Feb, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads