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)
Output:
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!
Recommended Blogs:
Multiline string in Python
Count the number of spaces in a string in Python
Leave a Reply