In Python, the str()
function is a built-in function that converts non-string data types into their string representations. It returns a string version of the given object. This function is particularly useful when you want to represent non-string objects as strings to display them or use them in string concatenation, formatting, or any other string operations.
The basic syntax of the str()
function is as follows:
str(object)
Here, object
is the non-string data type that you want to convert to a string.
Let's see some examples of how the str()
function works:
number = 42
string_number = str(number)
print(string_number) # Output: "42"
pi = 3.14159
string_pi = str(pi)
print(string_pi) # Output: "3.14159"
is_valid = True
string_is_valid = str(is_valid)
print(string_is_valid) # Output: "True"
my_list = [1, 2, 3]
string_list = str(my_list)
print(string_list) # Output: "[1, 2, 3]"
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def __str__(self):
return f"{self.name}, {self.age} years old"
person_obj = Person("Alice", 30)
string_person = str(person_obj)
print(string_person) # Output: "Alice, 30 years old"
In the last example, note that we defined a __str__
method within the Person
class. This special method allows us to define how the object should be represented as a string when the str()
function is called on it. By default, it would return something like <__main__.Person object at 0x...>
, but with the __str__
method, we can provide a custom string representation.
Remember that the str()
function can only convert objects to strings if there is a valid string representation for that object. Otherwise, it will raise an error. For custom objects, you can define the __str__
method as shown in Example 5 to customize the string representation.