Related Articles

# Python – Remove space between tuple elements

• Last Updated : 03 Jul, 2020

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.

 `# 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))`
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().

 `# 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))`
Output :
```The original tuple : (4, 5, 7, 6, 8)
The tuple after space removal : (4, 5, 7, 6, 8)
```

Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course

My Personal Notes arrow_drop_up