In Python, the str()
function serves as a versatile tool for converting objects to strings. This article endeavors to provide a comprehensive guide on its usage, applications, and significance through detailed examples.
Understanding str() Function
The str()
function in Python is utilized to convert objects to string representations. Its syntax is straightforward:
str(object)
Here, object
represents the object to be converted to a string.
Example 1: Basic Conversion
num = 123
str_num = str(num)
print("String representation of num:", str_num)
Output 1:
String representation of num: 123
Example 2: Conversion of Float
float_num = 3.14159
str_float = str(float_num)
print("String representation of float_num:", str_float)
Output 2:
String representation of float_num: 3.14159
Example 3: Conversion of List
my_list = [1, 2, 3, 4, 5]
str_list = str(my_list)
print("String representation of my_list:", str_list)
Output 3:
String representation of my_list: [1, 2, 3, 4, 5]
Example 4: Conversion of Custom Object
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def __str__(self):
return f"Name: {self.name}, Age: {self.age}"
person_obj = Person("John", 30)
str_person = str(person_obj)
print("String representation of person_obj:", str_person)
Output 4:
String representation of person_obj: Name: John, Age: 30
Points to Remember
- The
str()
function converts objects to string representations. - It is particularly useful for displaying object data or converting non-string objects to strings for manipulation.
- Custom objects can define a
__str__()
method to provide a custom string representation.