Python | Convert String to N chunks tuple

Sometimes, while working with Python Strings, we can have a problem in which we need to break a string to N sized chunks to a tuple. Let’s discuss certain ways in which this task can be performed.

Method #1 : Using list comprehension + tuple
This is one approach in which this task can be performed. In this, we just iterate the String and break the chunks of string and construct the tuple using tuple() in one liner.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 code to demonstrate working of
# Convert String to N chunks tuple
# Using list comprehension + tuple()
  
# initialize string
test_string = "ggggffffgggg"
  
# printing original string
print("The original string : " + str(test_string))
  
# initialize N 
N = 4
  
# Convert String to N chunks tuple
# Using list comprehension + tuple()
res = tuple(test_string[ i : i + N] for i in range(0, len(test_string), N))
  
# printing result
print("Chunked String into tuple : " + str(res))

chevron_right


Output :



The original string : ggggffffgggg
Chunked String into tuple : ('gggg', 'ffff', 'gggg')

 

Method #2 : Using zip() + iter() + join() + list comprehension
The combination of above functions can also be used to perform this task. In this, we perform the act of making chunks using zip() + iter(). And cummulate the result using join().

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 code to demonstrate working of
# Convert String to N chunks tuple
# Using zip() + iter() + join()+ list comprehension
  
# initialize string
test_string = "ggggffffgggg"
  
# printing original string
print("The original string : " + str(test_string))
  
# initialize N 
N = 4
  
# Convert String to N chunks tuple
# Using zip() + iter() + join() + list comprehension
res = tuple([''.join(ele) for ele in zip(*[iter(test_string)] * N)])
  
# printing result
print("Chunked String into tuple : " + str(res))

chevron_right


Output :

The original string : ggggffffgggg
Chunked String into tuple : ('gggg', 'ffff', 'gggg')


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.