Python – Remove space between tuple elements

Sometimes, while working with Tuples, we can have a problem in which we need to print tuples, with no space betweem the comma and next element, which by convention, is present. This problem can have use in day-day and school programming. Let’s discuss certain ways in which this task can be performed.

Input : test_tuple = (7, 6, 8)
Output : (7, 6, 8)

Input : test_tuple = (6, 8)
Output : (6, 8)

Method #1 : Using str() + replace()
The combination of above functions can be used to solve this problem. In this, we perform the task of removing the additional space, by replacing with empty space.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 code to demonstrate working of 
# Remove space between tuple elements
# Using replace() + str()
  
# initializing tuples
test_tuple = (4, 5, 7, 6, 8)
  
# printing original tuple
print("The original tuple : " + str(test_tuple))
  
# Remove space between tuple elements
# Using replace() + str()
res = str(test_tuple).replace(' ', '')
  
# printing result 
print("The tuple after space removal : " + str(res))

chevron_right


Output :



The original tuple : (4, 5, 7, 6, 8)
The tuple after space removal : (4, 5, 7, 6, 8)

 

Method #2 : Using join() + map()
Another method to solve this problem. In this, we perform the task of removal of space by external joining of each element using join() and extending the logic of string conversion to each element using map().

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 code to demonstrate working of 
# Remove space between tuple elements
# Using join() + map()
  
# initializing tuples
test_tuple = (4, 5, 7, 6, 8)
  
# printing original tuple
print("The original tuple : " + str(test_tuple))
  
# Remove space between tuple elements
# Using join() + map()
res = "(" + ", ".join(map(str, test_tuple)) + ")"
  
# printing result 
print("The tuple after space removal : " + str(res))

chevron_right


Output :

The original tuple : (4, 5, 7, 6, 8)
The tuple after space removal : (4, 5, 7, 6, 8)



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.