Converting a String to tuple in Python

Converting a String to tuple in Python

A string is a sequence of characters enclosed in quotes. It is immutable. Immutable meant if an object is created and value assigned and then you assign another value is assigned to the same object, the older value exists in memory.

A string is declared as below:

str = "py-programmers.blogspot.com"

-------------------

A tuple is a sequence of objects of different or same data types. The elements in tuple are separated by commas and all the elements are enclosed in round brackets/parentheses. Tuples can also be nested. Similar to string, tuple is also immutable. That is the only similarity between them. Usability wise both of them are different. 

A tuple is declared as below:

tup = ('1','2','3','4',"py-programmers.blogspot.com")

Below is the example of nested tuple:

tup1 = "way2know",tup

-------------------

A string can be converted to tuple using the tuple() function. Example is shown below:

string = "py-programming.blogspot.com"
print(tuple(string))

The above code prints:
('p', 'y', '-', 'p', 'r', 'o', 'g', 'r', 'a', 'm', 'm', 'i', 'n', 'g', '.', 'b', 'l', 'o', 'g', 's', 'p', 'o', 't', '.', 'c', 'o', 'm')

Post a Comment

0 Comments