Split a string into a Tuple in Python


Borislav Hadzhiev

Last updated: Aug 31, 2022


Photo from Unsplash

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.
my_str = 'one,two,three' # ✅ Split string into a tuple my_tuple = tuple(my_str.split(',')) print(my_tuple) # 👉️ ('one', 'two', 'three') # ------------------------------------- # 👇️ with trailing delimiter my_str = 'one,two,three,' my_tuple = tuple(my_str.split(',')[:-1]) print(my_tuple) # 👉️ ('one', 'two', 'three')

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

The method takes the following 2 parameters:

separatorSplit the string into substrings on each occurrence of the separator
maxsplitAt most maxsplit splits are done (optional)
my_str = 'one two three' my_tuple = tuple(my_str.split()) print(my_tuple) # 👉️ ('one', 'two', 'three')
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.

You can use list slicing to exclude the trailing delimiter if your string has one.

my_str = 'one, two, three, ' my_tuple = tuple(my_str.split(', ')[:-1]) print(my_tuple) # 👉️ ('one', 'two', 'three')

The syntax for list slicing is my_list[start:stop:step].

The start index is inclusive and the stop index is exclusive (up to, but not including).

Python indexes are zero-based, so the first item in a list has an index of 0, and the last item has an index of -1 or len(my_list) - 1.

We only specified a stop value, so the list slice goes up to, but not including the last list item.

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

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

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.