Python 101 : Turning a "String" into a "Tuple" using the constructor


We can easily convert a Sting into a tuple by using the constructor function of the class tuple

Tuples:

A tuple is a data type in Python that is ordered and immutable.
Tuples can contain elements of different types (Integers, strings, ...).

They are often used for data that doesn't change throughout the execution of a program. Below is a simple example of a tuple:



Constructors:

To create a new object and prepare it for use, we use the constructor of a class.
A constructor accepts arguments to set members of a class and also perform other setup actions before the object can be used.

The constructor method is called automatically when a new instance of a class is created. 
In Python the constructor is called __init__() . It takes arguments that are used to initialize the attributes of the class.

Below is a simple example of an "Employee" class:



In the following example, we are going to convert a String into a tuple by using the tuple constructor tuple().

The function returns the newly created tuple.

Below is a simple script that illustrates our example:


The above script defines a function convert_to_tuple() that takes a String and returns a tuple

Comments

Leave as a comment:

Archive