Python program to remove space between tuple elements

Here, we will simply learn how to remove space between the elements of a tuple while printing them on the output screen using Python program?
Submitted by Shivang Yadav, on September 23, 2021

In this program, we have a tuple consisting of multiple elements. And we need to create a program to remove space between the elements of the tuple.

Input:
myTup = (4, 3, 6, 1, 8)

Output: 
(4,3,6,1,8)

Before going further with the problem, let's recap some basic topics that will help in understanding the solution.

Python programming language is a high-level and object-oriented programming language. Python is an easy to learn, powerful high-level programming language. It has a simple but effective approach to object-oriented programming.

Tuples in Python is a collection of items similar to list with the difference that it is ordered and immutable.

Example:

tuple = ("python", "includehelp", 43, 54.23)

Now, let's get back to our topic of extracting even indexed elements in Tuple.

Removing space between tuple elements

For this, we will traverse the tuples and remove the spaces while printing them.

In the Python programming language, there are multiple ways using which we can remove spacing between tuple elements in python. Let's discuss some of them in the article,

Method 1:

To remove the extra space between tuples, we will simply use the replace() method which will replace the space between elements of tuple and then convert it string using the str() method.

# Python program to remove spaces 
# between elements of tuple 

# Creating and printing tuple...
myTuple = (6, 21, 8, 1, 9, 3)
print("Initial Tuple : " + str(myTuple))

# Removing spaces between elements of tuple 
spaceRemTuple = str(myTuple).replace(' ', '')

# printing space eliminated tuple 
print("Spaced Removed Tuple : " + str(spaceRemTuple))

Output:

Initial Tuple : (6, 21, 8, 1, 9, 3)
Spaced Removed Tuple : (6,21,8,1,9,3)

Method 2:

One more method to solve the problem is by removing the extra space from the tuple by using the join() method and then map it using the map() method.

# Python program to remove spaces 
# between elements of tuple 

# Creating and printing tuple...
myTuple = (6, 21, 8, 1, 9, 3)
print("Initial Tuple : " + str(myTuple))

# Removing spaces between elements of tuple 
spaceRemTuple = "(" + ",".join(map(str, myTuple)) + ")"

# printing space eliminated tuple 
print("Spaced Removed Tuple : " + str(spaceRemTuple))

Output:

Initial Tuple : (6, 21, 8, 1, 9, 3)
Spaced Removed Tuple : (6,21,8,1,9,3)

Python Tuple Programs »



Related Programs



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.