The str() function in Python is an in-built function that takes an object as input and returns its string representation. It can be used to convert various data types into strings, which can then be used for printing, concatenation, and formatting. Let’s take a simple example to converting an Integer to string.
Python
n = 123
s = str(n)
print(s)
Explanation: Here, integer 123 is passed to str() function, which returns the string '123'.
Syntax
str(object, encoding='utf-8', errors='strict')
Parameters:
- object (optional): The value to be converted. Can be any Python object (e.g., int, float, list, dict, bytes).
- encoding (optional): Used only when converting from bytes. Default is 'utf-8'.
- errors (optional): Specifies how to handle decoding errors:
- 'strict': Raises an error (default).
- 'ignore': Skips invalid characters.
- 'replace': Replaces invalid characters with ?.
Return Type:
- Returns a string representation of the object.
- Returns an empty string "" if no argument is passed.
Examples of str() function
Example 1. Converting an Integer to String
Python
n = 123
s = str(n)
print(s, type(s))
Explanation: The integer 123 is converted into the string '123'.
Example 2. Convert a Float to a String
Python
pi = 3.14159
s = str(pi)
print(s)
Explanation: The floating-point number 3.14159 is transformed into the string '3.14159'.
Example 3. Converting a List to a String
Python
a = [1, 2, 3]
s = str(a)
print(s)
Explanation: The list [1, 2, 3] is converted into the string representation '[1, 2, 3]'.
Example 4. Converting a Dictionary to a String
Python
b = {'name': 'Alice', 'age': 25}
s = str(b)
print(s)
Output{'name': 'Alice', 'age': 25}
Explanation: The dictionary {'name': 'Alice', 'age': 25} is represented as a string.
Example 5. Converting a Byte Object to String (with Encoding)
In this example, we’ll convert a byte object representing text into a string. By specifying the encoding, str() can correctly interpret the byte data as text.
Python
bd = b'Python programming'
txt = str(bd, encoding='utf-8')
print(txt)
Explanation: str(bd, encoding='utf-8') decodes the byte string using UTF-8.
Example 6. Handling Decoding Errors with errors='ignore'
Sometimes, byte data may contain invalid characters or sequences for a given encoding. The errors parameter allows us to control how these issues are handled. Using errors='ignore', we can skip invalid characters during conversion.
Python
bd = b'Hi \x80\x81'
t = str(bd, encoding='utf-8', errors='ignore')
print(t)
Explanation: Here, \x80 and \x81 are invalid UTF-8 byte sequences. By setting errors='ignore', these invalid characters are simply omitted from the output, resulting in a clean, readable string.
Example 7. Handling Decoding Errors with errors='replace'
Using errors='replace', we can substitute any problematic characters with a placeholder symbol (often a question mark, ?), so it’s clear where data was altered during conversion.
Python
bd = b'Hello world \x80\x81'
t = str(bd, encoding='utf-8', errors='replace')
print(t)
Explanation: invalid byte sequences \x80 and \x81 are replaced by ?, indicating that there were unrecognized characters in the data. This is helpful when we want to keep the original format of text without causing any errors when reading it.
Using errors='strict' raises a UnicodeDecodeError for any invalid byte sequence in the specified encoding, ensuring data conversion accuracy.
Python
bd = b'Hi \x80\x81'
try:
t = str(bd, encoding='utf-8', errors='strict')
print(t)
except UnicodeDecodeError as e:
print("Error:", e)
OutputError: 'utf-8' codec can't decode byte 0x80 in position 3: invalid start byte
Explanation: byte_data_invalid contains invalid UTF-8 sequences (\x80 and \x81). Using errors='strict' causes Python to raise a UnicodeDecodeError, stopping the conversion and providing an error message.
Common Use Cases:
- Convert values (like integers, floats, lists) to strings for printing or logging.
- Convert byte data to readable text using encoding.
- Handle decoding issues using errors parameter.
Read articles:
Similar Reads
Python - max() function
Python max() function returns the largest item in an iterable or the largest of two or more arguments. It has two forms. max() function with objectsmax() function with iterablePython max() function With ObjectsUnlike the max() function of C/C++, the max() function in Python can take any type of obje
4 min read
memoryview() in Python
The memoryview() function in Python is used to create a memory view object that allows us to access and manipulate the internal data of an object without copying it. This is particularly useful for handling large datasets efficiently because it avoids the overhead of copying data. A memory view obje
5 min read
Python min() Function
Python min() function returns the smallest value from a set of values or the smallest item in an iterable passed as its parameter. It's useful when you need to quickly determine the minimum value from a group of numbers or objects. For example:Pythona = [23,25,65,21,98] print(min(a)) b = ["banana",
4 min read
Python next() method
Python's next() function returns the next item of an iterator. Example Let us see a few examples to see how the next() method in Python works. Python3 l = [1, 2, 3] l_iter = iter(l) print(next(l_iter)) Output1 Note: The .next() method was a method for iterating over a sequence in Python 2.  It has
4 min read
Python oct() Function
Python oct() function takes an integer and returns the octal representation in a string format. In this article, we will see how we can convert an integer to an octal in Python. Python oct() Function SyntaxSyntax : oct(x) Parameters: x - Must be an integer number and can be in either binary, decimal
2 min read
ord() function in Python
Python ord() function returns the Unicode code of a given single character. It is a modern encoding standard that aims to represent every character in every language.Unicode includes:ASCII characters (first 128 code points)Emojis, currency symbols, accented characters, etc.For example, unicode of 'A
2 min read
pow() Function - Python
pow() function in Python is a built-in tool that calculates one number raised to the power of another. It also has an optional third part that gives the remainder when dividing the result. Example:Pythonprint(pow(3,2))Output9 Explanation: pow(3, 2) calculates 32 = 9, where the base is positive and t
2 min read
Python print() function
The python print() function as the name suggests is used to print a python object(s) in Python as standard output. Syntax: print(object(s), sep, end, file, flush) Parameters: Object(s): It can be any python object(s) like string, list, tuple, etc. But before printing all objects get converted into s
2 min read
Python range() function
The Python range() function returns a sequence of numbers, in a given range. The most common use of it is to iterate sequences on a sequence of numbers using Python loops.ExampleIn the given example, we are printing the number from 0 to 4.Pythonfor i in range(5): print(i, end=" ") print()Output:0 1
7 min read
Python reversed() Method
reversed() function in Python lets us go through a sequence like a list, tuple or string in reverse order without making a new copy. Instead of storing the reversed sequence, it gives us an iterator that yields elements one by one, saving memory. Example:Pythona = ["nano", "swift", "bolero", "BMW"]
3 min read