How to convert a String to a Tuple in Python

avatar
Borislav Hadzhiev

Last updated: Apr 9, 2024
7 min

banner

# Table of Contents

  1. Split a string into a Tuple in Python
  2. Convert a comma-separated string to a Tuple of integers
  3. Convert string representation of Tuple to Tuple in Python
  4. Convert a string to a tuple without splitting in Python
  5. Create a tuple from a string and a list of strings in Python

# Split a string into a Tuple in Python

To split a string into a tuple:

  1. Use the str.split() method to split the string into a list.
  2. Use the tuple() class to convert the list to a tuple.
main.py
my_str = 'bobby,hadz,com' my_tuple = tuple(my_str.split(',')) print(my_tuple) # ๐Ÿ‘‰๏ธ ('bobby', 'hadz', 'com')

split string into tuple

The code for this article is available on GitHub

If you need to convert a string to a tuple of integers, use the following code sample instead.

main.py
my_str = '1,2,3,4,5' my_tuple = tuple(int(item) if item.isdigit() else item for item in my_str.split(',')) print(my_tuple) # ๐Ÿ‘‰๏ธ (1, 2, 3, 4, 5)

The str.split() method splits the string into a list of substrings using a delimiter.

The method takes the following 2 parameters:

NameDescription
separatorSplit the string into substrings on each occurrence of the separator
maxsplitAt most maxsplit splits are done (optional)
main.py
my_str = 'bobby hadz com' my_tuple = tuple(my_str.split()) print(my_tuple) # ๐Ÿ‘‰๏ธ ('bobby', 'hadz', 'com')
When no separator is passed to the str.split() method, it splits the input string on one or more whitespace characters.

If the separator is not found in the string, a list containing only 1 element is returned.

# Exclude the leading and trailing delimiters before converting

You can use a generator expression to exclude the trailing delimiter if your string has one.

main.py
my_str = ',bobby,hadz,com,' my_tuple = tuple(item for item in my_str.split(',') if item) print(my_tuple) # ๐Ÿ‘‰๏ธ ('bobby', 'hadz', 'com')

exclude leading and trailing delimiters before converting

The code for this article is available on GitHub

The tuple class takes an iterable and returns a tuple object.

# Convert a comma-separated string to a Tuple of integers

To convert a comma-separated string to a tuple of integers:

  1. Use the str.split() method to split the string on each comma.
  2. Convert each item in the list to an integer.
  3. Use the tuple() class to convert the list to a tuple.
main.py
my_str = '1,2,3,4,5' my_tuple = tuple(int(item) if item.isdigit() else item for item in my_str.split(',')) print(my_tuple) # ๐Ÿ‘‰๏ธ (1, 2, 3, 4, 5)

convert comma separated string to tuple of integers

The code for this article is available on GitHub

We split the string on each comma and used a generator expression to iterate over the list.

Generator expressions are used to perform some operation for every element or select a subset of elements that meet a condition.

On each iteration, we check if the current item is a digit and use the int() class to convert the matching elements.

The str.isdigit() method returns True if all characters in the string are digits and there is at least 1 character, otherwise False is returned.

If you have a guarantee that the string only contains comma-separated integers, you can skip the call to the str.isdigit() method.

main.py
my_str = '1,2,3,4,5' my_tuple = tuple(int(item) for item in my_str.split(',')) print(my_tuple) # ๐Ÿ‘‰๏ธ (1, 2, 3, 4, 5)

If your string contains leading or trailing commas, use a generator expression to exclude the empty string elements.

main.py
my_str = ',one,two,three,four,five,' my_tuple = tuple(item for item in my_str.split(',') if item) print(my_tuple) # ๐Ÿ‘‰๏ธ ('one', 'two', 'three', 'four', 'five')

The string in the example has a leading and trailing comma, so splitting on a comma returns empty string elements.

main.py
my_str = ',one,two,three,four,five,' # ๐Ÿ‘‡๏ธ ['', 'one', 'two', 'three', 'four', 'five', ''] print(my_str.split(','))

You can use a generator expression to exclude the empty strings from the result.

# Convert string representation of Tuple to Tuple in Python

Use the ast.literal_eval() method to convert the string representation of a tuple to a tuple.

The ast.literal_eval() method allows us to safely evaluate a string that contains a Python literal.

main.py
from ast import literal_eval my_str = '(1,2,3,4)' # โœ… convert string representation of tuple to tuple (ast.literal_eval()) my_tuple = literal_eval(my_str) print(my_tuple) # ๐Ÿ‘‰๏ธ (1, 2, 3, 4) print(type(my_tuple)) # ๐Ÿ‘‰๏ธ <class 'tuple'>

convert string representation of tuple to tuple

The code for this article is available on GitHub

The example uses the ast.literal_eval() method to convert the string representation of a tuple to a tuple object.

The ast.literal_eval method allows us to safely evaluate a string that contains a Python literal.

The string may consist of strings, bytes, numbers, tuples, lists, dicts, sets, booleans and None.

If you have a string containing quoted elements, use the str.replace() method to remove the unnecessary quotes.

main.py
my_str = "('a','b','c','d')" my_tuple = tuple(my_str.strip('()').replace("'", '').split(',')) print(my_tuple) # ๐Ÿ‘‰๏ธ ('a', 'b', 'c', 'd')

We used the str.replace() method to remove the single quotes from the string before calling the str.split() method.

# Convert the string representation of a tuple to a tuple using map()

You can also use the map() function to convert the string representation of a tuple to a tuple.

main.py
my_tuple = tuple(map(int, my_str.strip('()').split(','))) print(my_tuple) # ๐Ÿ‘‰๏ธ (1, 2, 3, 4)
The code for this article is available on GitHub

We used the str.strip() method to remove the parentheses and split the string on each comma.

The map() function takes a function and an iterable as arguments and calls the function with each item of the iterable.

The map() function uses the int() class to convert each string to an integer.

# Convert a string to a tuple without splitting in Python

Here is an example of converting a string to a tuple without splitting.

main.py
my_str = 'one' my_tuple = (my_str,) print(my_tuple) # ๐Ÿ‘‰๏ธ ('one',) print(type(my_tuple)) # ๐Ÿ‘‰๏ธ <class 'tuple'>

We used a trailing comma to convert a string to a tuple without splitting.

If you pass the string to the tuple() class, you'd get a tuple containing the string's characters.

main.py
print(tuple('one')) # ๐Ÿ‘‰๏ธ ('o', 'n', 'e')

The tuple() class takes an iterable (e.g. a list or a string) and creates a tuple from it.

On the other hand, we can convert a string to a tuple by adding a trailing comma after the string.

As the documentation states construction of tuples with 1 item is done by following a value with a comma.

Note that enclosing the value in parentheses is not required, but makes your code more readable.

For example, both of these variables store a tuple with 1 item only.

main.py
my_str = 'one' my_tuple = (my_str,) my_tuple_2 = my_str,

It is not sufficient to wrap a single value in parentheses to create a tuple.

The trailing comma after the value is the difference between creating a tuple (with a trailing comma) or creating a value of a different type (without a trailing comma).

main.py
my_tuple_1 = ('one',) print(my_tuple_1) # ๐Ÿ‘‰๏ธ ('one',) print(type(my_tuple_1)) # ๐Ÿ‘‰๏ธ <class 'tuple'> my_str = ('one') print(my_str) # ๐Ÿ‘‰๏ธ 'one' print(type(my_str)) # ๐Ÿ‘‰๏ธ <class 'str'>

The first example uses a trailing comma after the value, so we end up creating a tuple.

The second example simply encloses a value in parentheses, so we end up creating a string.

Tuples are constructed in multiple ways:

  • Using a pair of parentheses () creates an empty tuple
  • Using a trailing comma - a, or (a,)
  • Separating items with commas - a, b or (a, b)
  • Using the tuple() constructor

The same syntax should be used when creating a list of tuples or using tuples as dictionary keys or values.

main.py
my_list = [('one',), ('two',), ('three',)] print(my_list[0]) # ๐Ÿ‘‰๏ธ ('one',) print(type(my_list[0])) # ๐Ÿ‘‰๏ธ <class 'tuple'>

Alternatively, you can use the tuple class if you don't like the implicit behavior of creating a tuple with a trailing comma.

main.py
my_str = 'one' my_tuple = tuple([my_str]) print(my_tuple) # ๐Ÿ‘‰๏ธ ('one',)
Notice that we wrapped the string in square brackets to pass a list instead of a string to the tuple() class.

This is important because had we passed a string to the class, we would get a tuple containing the string's characters.

# Create a tuple from a string and a list of strings in Python

To create a tuple from a string and a list of strings:

  1. Use a trailing comma to convert the string to a tuple.
  2. Use the tuple() class to convert the list to a tuple.
  3. Use the addition (+) operator to combine the two tuples.
main.py
my_str = 'bobby' my_list = ['hadz', 'com'] my_tuple = (my_str,) + tuple(my_list) print(my_tuple) # ๐Ÿ‘‰๏ธ ('bobby', 'hadz', 'com')
The code for this article is available on GitHub

Notice that we used a trailing comma to convert the string to a tuple with one element.

As the documentation states construction of tuples with 1 item is done by following a value with a comma.

main.py
my_str = 'bobby' tuple_1 = (my_str,) print(tuple_1) # ๐Ÿ‘‰๏ธ ('bobby', ) print(type(tuple_1)) # ๐Ÿ‘‰๏ธ <class 'tuple'>
Note that enclosing the value in parentheses is not required, but makes your code more readable.

It is not sufficient to wrap a single value in parentheses to create a tuple.

The trailing comma after the value is the difference between creating a tuple (with a trailing comma) or creating a value of a different type (without trailing comma).

The next step is to use the tuple() class to convert the list to a tuple.

main.py
my_str = 'bobby' my_list = ['hadz', 'com'] tuple_1 = (my_str,) tuple_2 = tuple(my_list) print(tuple_2) # ๐Ÿ‘‰๏ธ ('hadz', 'com')

The tuple class takes at most 1 argument - an iterable and converts the iterable to a tuple.

We didn't use the tuple() class to convert the string to a tuple because passing a string to the class would get us a tuple containing the string's characters.

main.py
my_str = 'one' print(tuple(my_str)) # ๐Ÿ‘‰๏ธ ('o', 'n', 'e')

The last step is to use the addition operator to combine the two tuples.

main.py
my_str = 'bobby' my_list = ['hadz', 'com'] tuple_1 = (my_str,) tuple_2 = tuple(my_list) my_tuple = tuple_1 + tuple_2 print(my_tuple) # ๐Ÿ‘‰๏ธ ('bobby', 'hadz', 'com')

When used with two or more tuples, the addition (+) operator combines the tuples.

main.py
# ๐Ÿ‘‡๏ธ ('bobby', 'hadz', 'com') print(('bobby',) + ('hadz', 'com'))

Alternatively, you can wrap the string in square brackets and use the tuple() class.

# Create a tuple from a string and a list of strings addition (+) operator

This is a three-step process:

  1. Wrap the string in square brackets to get a list.
  2. Use the addition operator to combine the two lists.
  3. Use the tuple() class to convert the result to a tuple.
main.py
my_str = 'bobby' my_list = ['hadz', 'com'] my_tuple = tuple([my_str] + my_list) print(my_tuple) # ๐Ÿ‘‰๏ธ ('bobby', 'hadz', 'com')
The code for this article is available on GitHub

The values on the left-hand and right-hand sides of the addition (+) operator are lists, so the two lists get merged.

main.py
my_str = 'bobby' my_list = ['hadz', 'com'] # ๐Ÿ‘‡๏ธ ['bobby', 'hadz', 'com'] print([my_str] + my_list)

The last step is to pass the list to the tuple() class to convert it to a tuple.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.

Copyright ยฉ 2024 Borislav Hadzhiev