Python str() Function

Python Built In Str() Function

This is a detailed tutorial of the Python built-in str() Function. Learn to convert a given Python Object into a String type object using this method.

Python str() Function

The Python function str() converts a given Python object into a String type object and returns it.

This is one of the most commonly used built-in functions. Often, we need to print different types of objects and their values to console as a string and this function helps there.

Syntax

The syntax of the str() function is given below.

str() Parameters

This function can take up to three different arguments that are described below.

  • object. This is the object which you want to convert into its corresponding string form. In case, you do not provide this argument, the str() function will return an empty string.
  • encoding. You can specify the encoding of the string that you passed as the object in the first argument. By default, it assumes the encoding to be UTF-8 as it’s the default value for the encoding argument.
  • errors. This is an argument to define the action against the errors. For what type of encoding errors, partial or complete, this function should raise errors, that you have to define in this argument. The default value of this argument is 'strict'.

You can specify the following type of errors to the third argument. These are described below.

  • strict – If the decoding fails, this function will raise the UnicodeDecodeError exception,
  • ignore – It will ignore the part of the code that is not encodable.
  • replace – The part of the string that is not encodable will be replaced by the question mark symbols.
  • xmlcharrefreplace – XML character reference will be specified in place of the unencodable characters of the given string.
  • backslashreplace – In place of the characters that are not encodable, the escape sequence \uNNNN will be printed.
  • namereplace – In place of the characters that are not encodable, the escape sequence \N{...} will be printed.

str() Return Value

It returns a Python String type object for the given object passed in the argument of this function. This object can be directly printed to the console and we can apply all of the string methods on it as like any other string type object.

Examples

Given below are the three different examples illustrating the usage of the Python built-in str() function.

Example 1. Converting Python Built-in Data Types into Strings

In this example, we’re converting some of the built-in data types objects such as integer & floating-point numbers, sequence objects like Tuples & Dictionaries into string type objects using the function str(). After conversion, we’re simply printing them to the console.

#Integer To String Conversion
num1 = 10
print("Type of num1 is", type(num1))
num1_string = str(num1)
print("Type of", num1_string, "is", type(num1_string))

#Floating-Point To String Conversion
num2 = 5.678
print("Type of num2 is", type(num2))
num2_string = str(num2)
print("Type of", num2_string, "is", type(num2_string))

#List To String Conversion
list1 = [1, 2, 3, 4, 5]
print("Type of list1 is", type(list1))
list1_string = str(list1)
print("Type of", list1_string, "is", type(list1_string))

#List To String Conversion
dict1 = {
    0: False,
    1: True
}
print("Type of dict1 is", type(dict1))
dict1_string = str(dict1)
print("Type of", dict1_string, "is", type(dict1_string))

Output.

Example 2. Converting Custom Class Objects using str() function

This example is to illustrate the concept that when you apply the str() function for a given object, this function internally calls the method __str__() for the class associated with that object. But if it does not found the __str__() method defined for the class belonging to the object, it rather calls the repr(obj) method.

class Marks:
    def __str__(self):
        return "Marks Object String!"
        
obj1 = Marks()
print("Type of obj1 is", type(obj1))
#Calling str() for obj1
print(str(obj1))

class Demo:
    total = 500
        
obj2 = Demo()
print("Type of obj2 is", type(obj2))
#Calling str() for obj2
print(str(obj2))

print(repr(obj2))

Output.

As you can see in the case of obj1, it returns what is being returned the internal method __str__() of class Marks. In the second case, the class Demo to which obj2 belongs does not have this method, so it simply returns what is being returned by repr(obj2).

Example 3. Working of str() for bytes objects

If you are also passing the encoding and the errors arguments, then the first argument that is the object argument should be a bytes-like object i.e. either a bytes object or bytearray object.

In case the object passed in the first argument is either a bytes or bytearray object, the str() function internally calls the method bytes.decode(encoding, errors). In all other cases, the bytes object is taken in the buffer before the method decode() is being called.

#Creating a Bytes Object using bytes() function
obj = bytes('Hello, नमस्कार!', encoding = 'utf-8')

print(obj)

obj_string = str(obj, encoding = "ascii", errors = "replace")

print(obj_string)

Output.

We’ve first created a bytes object using the built-in function bytes(). This bytes object contains a string that is the UTF-8 format. Now, we’re using the str() function to convert this object into ASCII string. But as the obj string also contains UTF-8 characters, there will be some characters that may not be converted using the ASCII encoding. That’s why we’ve specified the third argument i.e. errors = "replace" to replace all of such unencodable characters into question marks.

I hope you found this guide useful. If so, do share it with others who are willing to learn Python and other programming languages. If you have any questions related to this article, feel free to ask us in the comments section.

And do not forget to subscribe to WTMatter!

Subscribe To WTMatter!

Receive updates of our latest articles via email. Enter your email address below to get started.

Leave a Reply

Your email address will not be published. Required fields are marked *