Last updated: Apr 9, 2024
Reading timeยท7 min
To split a string into a tuple:
str.split()
method to split the string into a list.tuple()
class to convert the list to a tuple.my_str = 'bobby,hadz,com' my_tuple = tuple(my_str.split(',')) print(my_tuple) # ๐๏ธ ('bobby', 'hadz', 'com')
If you need to convert a string to a tuple of integers, use the following code sample instead.
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:
Name | Description |
---|---|
separator | Split the string into substrings on each occurrence of the separator |
maxsplit | At most maxsplit splits are done (optional) |
my_str = 'bobby hadz com' my_tuple = tuple(my_str.split()) print(my_tuple) # ๐๏ธ ('bobby', 'hadz', 'com')
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 a generator expression to exclude the trailing delimiter if your string has one.
my_str = ',bobby,hadz,com,' my_tuple = tuple(item for item in my_str.split(',') if item) print(my_tuple) # ๐๏ธ ('bobby', 'hadz', 'com')
The tuple class
takes an iterable and returns a tuple
object.
To convert a comma-separated string to a tuple of integers:
str.split()
method to split the string on each comma.tuple()
class to convert the list to a tuple.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)
We split the string on each comma and used a generator expression to iterate over the list.
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.
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.
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.
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.
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.
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'>
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.
If you have a string containing quoted elements, use the str.replace()
method
to remove the unnecessary quotes.
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.
You can also use the map()
function to convert the string representation of a
tuple to a tuple.
my_tuple = tuple(map(int, my_str.strip('()').split(','))) print(my_tuple) # ๐๏ธ (1, 2, 3, 4)
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.
Here is an example of converting a string to a tuple without splitting.
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.
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.
For example, both of these variables store a tuple with 1 item only.
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).
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:
()
creates an empty tuplea,
or (a,)
a, b
or (a, b)
tuple()
constructorThe same syntax should be used when creating a list of tuples or using tuples as dictionary keys or values.
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.
my_str = 'one' my_tuple = tuple([my_str]) print(my_tuple) # ๐๏ธ ('one',)
tuple()
class.This is important because had we passed a string to the class, we would get a tuple containing the string's characters.
To create a tuple from a string and a list of strings:
tuple()
class to convert the list to a tuple.my_str = 'bobby' my_list = ['hadz', 'com'] my_tuple = (my_str,) + tuple(my_list) print(my_tuple) # ๐๏ธ ('bobby', 'hadz', 'com')
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.
my_str = 'bobby' tuple_1 = (my_str,) print(tuple_1) # ๐๏ธ ('bobby', ) print(type(tuple_1)) # ๐๏ธ <class 'tuple'>
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.
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.
my_str = 'one' print(tuple(my_str)) # ๐๏ธ ('o', 'n', 'e')
The last step is to use the addition operator to combine the two tuples.
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.
# ๐๏ธ ('bobby', 'hadz', 'com') print(('bobby',) + ('hadz', 'com'))
Alternatively, you can wrap the string in square brackets and use the tuple()
class.
This is a three-step process:
tuple()
class to convert the result to a tuple.my_str = 'bobby' my_list = ['hadz', 'com'] my_tuple = tuple([my_str] + my_list) print(my_tuple) # ๐๏ธ ('bobby', 'hadz', 'com')
The values on the left-hand and right-hand sides of the addition (+) operator are lists, so the two lists get merged.
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.
You can learn more about the related topics by checking out the following tutorials: