To convert a string into a tuple using Python, use the tuple() function.

string = "hello"

t = tuple(string)

print(t)

#Output:
('h', 'e', 'l', 'l', 'o')

When working with different objects in Python, the ability to be able to convert objects into other objects can be valuable.

One such situation is if you want to convert a string to a tuple.

To convert a string into a tuple using Python, use the tuple() function.

Below is a simple example of how you can convert a string into a tuple using tuple() in Python.

string = "hello"

t = tuple(string)

print(t)

#Output:
('h', 'e', 'l', 'l', 'o')

Convert Tuple to String in Python

To go the other way and convert a tuple into a string, it’s not quite as easy as just converting the tuple into a string with the Python str() function.

To convert a tuple into a string, you can instead use the string join() function.

Below is a simple example of how you can convert a tuple into a string in Python.

t = ('h', 'e', 'l', 'l', 'o')

s = "".join(t)

print(s)

#Output:
hello

Using tuple() to Convert Other Objects to Tuples in Python

You can also use the Python tuple() function to convert other objects into tuples.

One such example is if you want to convert a list into a tuple in your Python code.

To do so, you can slightly modify the example from above.

Below is a simple example showing you how to convert a list into a tuple using Python.

lst = [0, 1, 2, 3]

t = tuple(lst)

print(t)

#Output:
(0, 1, 2, 3)

Hopefully this article has been useful for you to learn how to convert a string into a tuple in Python.

Categorized in:

Python,

Last Update: March 22, 2024