In Python, the str() function is a built-in function used to convert an object into a string. This function can be used to convert integers, floats, lists, tuples, dictionaries, and other data types to string data type.
Syntax:
The syntax of the str() function is as follows:
|
str(object, encoding='utf-8', errors='strict')
|
Here, object is the object that needs to be converted to a string. The optional encoding and errors parameters specify the encoding to be used for the conversion and the error handling mechanism to be used if the conversion fails.
Examples:
Let's take a look at some examples of using the str() function:
|
x = 42
str_x = str(x)
print(str_x)
|
Output:
'42'
In this example, we convert the integer 42 to a string using the str() function.
|
my_list = [1, 2, 3, 4, 5]
str_list = str(my_list)
print(str_list)
|
Output:
[1, 2, 3, 4, 5]
In this example, we convert a list to a string using the str() function.
|
my_tuple = (1, 2, 3, 4, 5)
str_tuple = str(my_tuple)
print(str_tuple)
|
Output:
(1, 2, 3, 4, 5)
In this example, we convert a tuple to a string using the str() function.
|
my_dict = {'name': 'John', 'age': 30}
str_dict = str(my_dict)
print(str_dict)
|
Output:
{'name': 'John', 'age': 30}
In this example, we convert a dictionary to a string using the str() function.
Conclusion:
In conclusion, the str() function is a useful built-in function in Python that can be used to convert various data types to string data type. It is commonly used in print statements, file writing, and other string manipulations in Python.