Skip to main content

Python str() Function

The str() method returns the string representation of a given object.

It can be applied to various datatypes such as numbers but also custom objects.

Syntax

str(object, encoding, errors)

str() Parameters

Python str() function parameters:

ParameterConditionDescription
objectRequiredThe object that needs to be converted to a string.
encodingOptionalThe encoding of the object. Default is UTF-8
errorsOptionalSpecifies what to do if the decoding fails
warning

encoding and errors parameters are only meant to be used when the object type is bytes or bytearray.

str() Return Value

Python str() function returns the string representation of the given object.

Examples

Example 1: Converting an Integer to String

The str() function can be used to convert an integer to a string. The type() function confirms that the result is indeed a string.

num =  123
str_num = str(num)
print(str_num) # Output: 123
print(type(str_num)) # Output: <class 'str'>

output

123
<class 'str'>

Example 2: Converting a Floating-Point Number to String

The str() function can be used to convert an integer to a string. The type() function confirms that the result is indeed a string.

num =  123.45
str_num = str(num)
print(str_num) # Output: 123.45
print(type(str_num)) # Output: <class 'str'>

output

123.45
<class 'str'>

Example 3: Converting Tuple to String

Converting a tuple to a string in Python can be achieved using the str() function, which converts an object into a string.

my_tuple = ('p', 'y', 't', 'h', 'o', 'n')
tuple_str = str(my_tuple)
print(tuple_str)
print(type(tuple_str))

output

('p', 'y', 't', 'h', 'o', 'n')
<class 'str'>

However, when dealing with tuples, you might want to control how the elements are joined together.

tuples = ('Tutorial', ' Reference', ' -',' tutorialreference', '.com')

def convertTuple(tuples):
str = ''.join(map(str, tuples))
return str

string = convertTuple(tuples)
print(string)

output

Tutorial Reference - tutorialreference.com

Example 4: Converting Dictionary to String

Converting a dictionary to a string in Python can be achieved using the str() function, which converts an object into a string.

my_dict = {'name': 'Tom', 'age':  25, 'city': 'New York'}
dict_str = str(my_dict)
print(dict_str)
print(type(dict_str))

output

{'name': 'Tom', 'age': 25, 'city': 'New York'}
<class 'str'>

However, when dealing with dictionary, you might want to control how the key-value pairs are represented.

my_dict = {'name': 'Tom', 'age':  25, 'city': 'New York'}

# Convert the dictionary to a list of key-value pairs
kv_pairs = [f"{k}: {v}" for k, v in my_dict.items()]

# Join the key-value pairs into a single string
str_dict = ', '.join(kv_pairs)
print(str_dict)

output

name: Tom, age: 25, city: New York

Example 5: Converting a Custom Object to String

You can use str() function with Custom Objects: you need to implement the __str__() method in your class because this function will be used by the str() function.

For example, implement the Person class with __str__() method. Then invoke str() function with an instance of the Person class as argument:

class Person:
def __init__(self, name, age):
self.name = name
self.age = age

def __str__(self):
return f"Person(name={self.name}, age={self.age})"

p = Person("Tom", 25)
print(str(p)) # Output: Person(name=Tom, age=25)

output

Person(name=Tom, age=25)

Example 6: Converting Bytes Objects to String

str() can be used with the encoding and errors parameters to handle bytes.

The encoding parameter specifies the character encoding to use, and the errors parameter defines how to handle decoding errors. In this case, the str() function converts bytes to a string, ignoring any characters that can not be decoded using ASCII encoding.

bytes_obj = bytes("String", encoding='utf-8')
converted_string = str(bytes_obj, encoding="ascii", errors="ignore")
print(converted_string) # Output: String

output

String

str() function for bytes and bytearray

The str() function can also work with bytes and bytearray objects.

In this case, encoding and errors parameters are required!

There are six types of errors:

  • strict: This is the default mode. In strict mode, encoding errors raise a UnicodeEncodeError or UnicodeDecodeError exception. This mode ensures that the conversion process is strict and adheres to the encoding's rules, making it suitable for situations where it's crucial to preserve the integrity of the data.
  • ignore: In this mode, errors are silently ignored, and the offending characters are simply omitted from the output. This can be useful when you want to process as much of the data as possible without stopping at the first error.
  • replace: This mode replaces any characters that can not be encoded or decoded with the Unicode replacement character U+FFFD. This is helpful when you want to ensure that the output string is always complete, even if some characters can not be represented.
  • xmlcharrefreplace: This mode replaces any characters that can not be encoded with an XML character reference. For example, the character U+20AC (€) would be replaced with &#8364;. This is particularly useful when working with XML data that needs to be encoded in a specific encoding.
  • namereplace: Similar to xmlcharrefreplace, this mode replaces characters that can not be encoded with a Unicode character reference, but it uses the character's name instead of its numeric value. For example, the character U+20AC (€) would be replaced with &#x20AC; or &#8364; depending on whether the encoding is ASCII or UTF-8.
  • backslashreplace: In this mode, any characters that can not be encoded are replaced with a backslashed escape sequence. For example, the character U+20AC (€) would be replaced with \u20AC. This mode is useful when you need to preserve the exact bytes of the original data in the encoded string.
note

The default error type is strict.