You are currently viewing Python str() Method

The Python str() method is used to convert an object into a string representation. It is a built-in function that can be used to convert objects of different data types, such as integers, floats, lists, or dictionaries, into a string format. The str() function returns a human-readable string representation of the input object.

Advertisements

In this article, I will explain the str() method in detail, including its syntax, parameters, and different use cases with examples.

1. Quick Examples of Python str() method

Below are some quick examples of using the str() function. You can have a high level of idea of how to use the python str() method, more details are provided in the coming sections.


# Quick Examples of str() method.

# Example 1: Converting integers to strings
num = 24
print(str(num)) 

# Example 2: Converting floats to strings
float_num = 6.28
print(str(float_num)) 

# Example 3: Converting lists to strings
list = [4, 5, 6]
print(str(list))  

# Example 4: Converting dictionaries to strings
dictionary = {'name': 'Jane', 'age': 20}
print(str(dictionary))

# Example 5: Converting tuples to strings
tuple = (4, 5, 6)
print(str(tuple)) 

# Example 6: Converting sets to strings
set = {4, 5, 6}
print(str(set))  

# Example 7: Converting booleans to strings
boolean = False
print(str(boolean)) 

2. Syntax of Python str() Method

Normally we only pass an object to the python str() method, however, it can take two additional parameters as well. Below is the syntax of python str() method.


# Syntax of str()
str(object, encoding='utf-8', errors='strict')

2.1 Parameters of the str() Method

The Python str() method takes one required and two optional parameters:

  • object: It can be any data type, such as integers, floats, lists, dictionaries, tuples, sets, booleans, or custom objects. If it is already a string, the str() method returns the same string without any change.
  • encoding: The encoding to use for the string representation. The default value is 'utf-8'. However you can use other encoding methods like 'utf-16' and others.
  • errors: The default value is 'strict', which raises an error if the encoding fails. Other possible values are 'ignore' and 'replace', which respectively ignore and replace encoding errors.

2.2 Return Value of str() Method

The return value of the str() function is a string object.

2.3 Example of str() Using all Parameters

See the following example, where we have used all required and optional parameters of the str() method.


# Define a byte object
object = b'SparkByExamples.Com'

# Convert the object to string representation 
string = str(object, encoding='utf-16', errors='ignore')

# Print the string representation
print(string) 

# Output: 
# '灓牡䉫䕹慸灭敬⹳潃'

3. str() Convert Integers to String

The str() method can also be used to convert integers to strings. This can be useful when you need to represent a number as a string, for example, for printing, concatenation with other strings, or for storing in a file or database.


# Convert int to string
integer = 12345
string_ = str(integer)
print(string_r)  

# Output: '12345'

integer = -42
string_r = str(integer)
print(string_r) 
 
# Output: '-42'

# Example 3
integer = 0
string_r = str(integer)
print(string_r)  

# Output: '0'

In the same way, you can convert floats to strings in python using the str() method. It works the same way for floating point data as it worked for integers.

4. str() – Convert Lists to Strings

Let’s say you want to convert a python list to a string, in this case, you can use the str() method.


# A list is defined
my_list = [6, 7, 8, 9, 10]

# The list is then converted to a string representation
string_version = str(my_list)

# The string representation is printed
print(string_version)  
# Output: '[6, 7, 8, 9, 10]'

5. str() – Convert Dictionaries to Strings

To Convert a python Dictionary you can use the str() method. This can be useful when you need to represent a dictionary as a string.


# Define a dictionary
dct = {'Site': 'SparkByExample', 'Niche': 'Programming'}

# Dictionary to a string representation
string_representation = str(dct)

# Print the string representation
print(string_representation)  
# Output: " {'Site': 'SparkByExample', 'Niche': 'Programming'}"

6. str() – Convert Tuples to Strings

You can also use this method to convert a python tuple to a string. See the following example.


# Define a tuple
tple = ('Python', 'Java', 'Spark')

# Tuple to a string representation
string_representation = str(tple)

# Print the string representation
print(string_representation)  
# Output: "('Python', 'Java', 'Spark')"

7. str() – Convert Sets to Strings

The Python str() method can also be used to convert a python set to a Python String. See the following example.


# Define a set
st = {'python', 'java', 'spark'}

# set to a string representation
string_representation = str(st)

# Print the string representation
print(string_representation)  
# Output: "{'python', 'java', 'spark'}"

8. str() – Convert Booleans to Strings

You can also use the python str() method to convert a boolean value to its string representation. Below is an example.


# Boolean value to a string representation
string_representation = str(True)

# Print the string representation
print(string_representation)  
# Output: "True"

9. str() – Convert Objects to Strings

An object is any user-defined class, data structure, or custom data type. We can use the Python str() method to convert these objects to strings.

By default, the str() method returns a string representation of the object’s memory location, which may not be useful in many cases.

In such cases, you can define a special method __str__ in your class to provide a human-readable string representation of your object. The __str__ method should return a string that describes the object in a meaningful way.


class Animal:
    def __init__(self, name, age):
        self.name = name
        self.age = age
    def __str__(self):
        return f'Animal(name={self.name}, age={self.age})'

animal = Animal('Lion', 5)

# Convert the Animal object to a string representation
string_representation = str(animal)

# Print the string representation
print(string_representation)  
# Output: "Animal(name=Lion, age=5)"

Summary and Conclusion

We have discussed python str() method with examples. You have learned how we can use the str() method to convert python lists, sets, tuples, and other objects to python strings. I hope this tutorial has given you a good idea of how to use the python str() method. If you still have any questions please comment below.

Happy Learning!