# Convert String to Tuple in Python

PythonServer Side ProgrammingProgramming

When it is required to convert a string into a tuple, the 'map' method, the 'tuple' method, the 'int' method, and the 'split' method can be used.

The map function applies a given function/operation to every item in an iterable (such as list, tuple). It returns a list as the result.

The 'int' method converts the given data type to an integer type, if that operation is permitted.

The split method splits the given data into different sections based on a delimiter or a default delimiter. The 'tuple' method converts the given data type into a tuple type.

Below is a demonstration of the same −

## Example

Live Demo

my_str_1 = "7, 8, 0, 3, 45, 3, 2, 22, 4"

print ("The string is : " )
print(my_str_1)

my_result = tuple(map(int, my_str_1.split(', ')))

print("The tuple after converting from a string is : ")
print(my_result)

## Output

The string is :
7, 8, 0, 3, 45, 3, 2, 22, 4
The tuple after converting from a string is :
(7, 8, 0, 3, 45, 3, 2, 22, 4)

## Explanation

• A string is defined and is displayed on the console.
• The string is split, and every element is converted to an integer, and this operation is applied to every element using the 'map' method.
• This is again converted to a tuple type.
• This result is assigned to a value.
• It is displayed as output on the console.
Published on 11-Mar-2021 10:01:02