- Comma-separated string to tuple in Python
- Syntax of split():
- Program to convert the comma-separated string to a tuple in Python
- Python from string to tuple
- # Table of Contents
- # Split a string into a Tuple in Python
- # Exclude the leading and trailing delimiters before converting
- # Convert a comma-separated string to a Tuple of integers
- # Convert string representation of Tuple to Tuple in Python
- # Convert the string representation of a tuple to a tuple using map()
- # Convert a string to a tuple without splitting in Python
- # Create a tuple from a string and a list of strings in Python
- # Create a tuple from a string and a list of strings addition (+) operator
- # Additional Resources
Comma-separated string to tuple in Python
In this tutorial, we will learn how to convert the comma-separated string to a tuple in Python.
Before proceeding to the solution, let us understand the problem first with a simple example:
Consider a comma-separated input string. Our task is to convert the given string to a tuple. We can use the built-in string method split() to fetch each of the comma-separated string into a list and then convert it to a tuple.
Syntax of split():
inputstring.split(seperator=None, maxsplit=-1)
It uses the separator as the delimiter string and returns a list of words from the string. The maxsplit specifies the maximum splits to be done. If it is -1 or not specified then all possible number of splits are made.
For example:
>>> 'Hi Bye Go'.split() ['Hi', 'Bye', 'Go'] >>> 'Hi Bye Go'.split(maxsplit=1) ['Hi', 'Bye Go'] >>> 'Hi,Bye,,Go,'.split(',') ['Hi', 'Bye', '', 'Go', '']
Program to convert the comma-separated string to a tuple in Python
inpstr = input ("Enter comma-separated string: ") print ("Input string given by user: ", inpstr) tuple = tuple(inpstr.split (",")) print("Tuple containing comma-separated string is: ",tuple)
Enter comma-separated string: Hi,Bye,Go Input string given by user: Hi,Bye,Go Tuple containing comma-separated string is: ('Hi', 'Bye', 'Go')
This program takes an input string from the user containing comma-separated elements. It then displays the same to the user. Then, it uses the split() method to separate the individual elements in the string and this method returns a list of these elements. This list is explicitly converted to a tuple and the contents of the tuple are printed on the screen.
I hope this tutorial helped you in clearing your concepts. Happy learning!
Python from string to tuple
Last updated: Feb 21, 2023
Reading time · 7 min
# Table of Contents
# Split a string into a Tuple in Python
To split a string into a tuple:
- Use the str.split() method to split the string into a list.
- Use the tuple() class to convert the list to a tuple.
Copied!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.
Copied!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) |
Copied!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.
Copied!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.
# Convert a comma-separated string to a Tuple of integers
To convert a comma-separated string to a tuple of integers:
- Use the str.split() method to split the string on each comma.
- Convert each item in the list to an integer.
- Use the tuple() class to convert the list to a tuple.
Copied!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.
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.
Copied!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.
Copied!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.
Copied!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.
Copied!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)) # 👉️
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.
Copied!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.
Copied!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.
# Convert a string to a tuple without splitting in Python
Here is an example of converting a string to a tuple without splitting.
Copied!my_str = 'one' my_tuple = (my_str,) print(my_tuple) # 👉️ ('one',) print(type(my_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.
Copied!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.
Copied!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).
Copied!my_tuple_1 = ('one',) print(my_tuple_1) # 👉️ ('one',) print(type(my_tuple_1)) # 👉️ my_str = ('one') print(my_str) # 👉️ 'one' print(type(my_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.
Copied!my_list = [('one',), ('two',), ('three',)] print(my_list[0]) # 👉️ ('one',) print(type(my_list[0])) # 👉️
Alternatively, you can use the tuple class if you don’t like the implicit behavior of creating a tuple with a trailing comma.
Copied!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:
- Use a trailing comma to convert the string to a tuple.
- Use the tuple() class to convert the list to a tuple.
- Use the addition (+) operator to combine the two tuples.
Copied!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.
Copied!my_str = 'bobby' tuple_1 = (my_str,) print(tuple_1) # 👉️ ('bobby', ) print(type(tuple_1)) # 👉️
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 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.
Copied!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.
Copied!my_str = 'one' print(tuple(my_str)) # 👉️ ('o', 'n', 'e')
The last step is to use the addition operator to combine the two tuples.
Copied!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.
Copied!# 👇️ ('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:
- Wrap the string in square brackets to get a list.
- Use the addition operator to combine the two lists.
- Use the tuple() class to convert the result to a tuple.
Copied!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.
Copied!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.