GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Python Tutorial
  • Data Types
  • Interview Questions
  • Examples
  • Quizzes
  • DSA Python
  • Data Science
  • NumPy
  • Pandas
  • Practice
  • Django
  • Flask
  • byte object
  • encoding

This view

  • Original page
  • New address

GeezerVison is showing www.geeksforgeeks.org — Python str() function - GeeksforGeeks

geeksforgeeks
search icon
  • Courses
  • Tutorials
  • Interview Prep
  • Python Tutorial
  • Data Types
  • Interview Questions
  • Examples
  • Quizzes
  • DSA Python
  • Data Science
  • NumPy
  • Pandas
  • Practice
  • Django
  • Flask

Python str() function

Last Updated : 15 Jul, 2025

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)

Output
123

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))

Output
123 <class 'str'>

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)

Output
3.14159

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)

Output
[1, 2, 3]

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)

Output
Python programming

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)

Output
Hi 

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)

Output
Hello world ��

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.

Example 8. Raising an Error on Invalid Bytes with errors='strict'

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)

Output
Error: '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:

  • byte object
  • encoding
  • decoding
Comment

Explore

    Python Fundamentals
    • Introduction1 min read
    • Input & Output2 min read
    • Variables4 min read
    • Operators4 min read
    • Keywords2 min read
    • Data Types4 min read
    • Conditional Statements3 min read
    • Loops3 min read
    • Functions4 min read
    Python Data Structures
    • String4 min read
    • List3 min read
    • Tuples3 min read
    • Dictionary3 min read
    • Set2 min read
    • Arrays5 min read
    Advanced Python
    • OOP Concepts3 min read
    • Exception Handling5 min read
    • File Handling4 min read
    • Python Database2 min read
    • MongoDB3 min read
    • MySQL7 min read
    • Packages4 min read
    • Modules3 min read
    • DSA Libraries5 min read
    • Python GUI2 min read
    Data Science with Python
    • Numpy3 min read
    • Pandas4 min read
    • Matplotlib3 min read
    • Seaborn3 min read
    • StatsModel2 min read
    • Model Building6 min read
    • TensorFlow2 min read
    • PyTorch5 min read
    Web Development with Python
    • Flask3 min read
    • Django5 min read
    • Django ORM4 min read
    • Jinja2 Templating5 min read
    • Django Templates5 min read
    • REST API3 min read
    • Build API with DRF4 min read
    Python Practice
    • Quiz1 min read
    • Practice Problems2 min read
    • Interview Q & A15+ min read
    Courses
    • Placement 360 Course2 min read
    • Data Science 360 Course2 min read
    • AI Engg Course2 min read
You are visitor 01402503 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.