Python str()
Function
The str()
function in Python is used to convert values into a string format. Whether it’s a number, a list, or an object, str()
gives you the string version of it.
Syntax
str(object='', encoding='utf-8', errors='strict')
Parameters:
object
(optional) – The object you want to convert to a string.encoding
(optional) – Only used if the object is a bytes-like object.errors
(optional) – Specifies how to handle encoding errors.
Returns:
- A string version of the specified object.
Example 1: Converting Numbers to Strings
x = 123
print(str(x))
'123'
Example 2: Converting a List to a String
my_list = [1, 2, 3]
print(str(my_list))
'[1, 2, 3]'
Example 3: Using str()
with a Float
pi = 3.14159
print(str(pi))
'3.14159'
Use Case: String Concatenation
Sometimes you want to add text and numbers together. You need to convert the number into a string first:
name = "Alice"
age = 25
print("Name: " + name + ", Age: " + str(age))
Name: Alice, Age: 25
Special Case: Encoding and Decoding Bytes
b = b"hello"
print(str(b, encoding="utf-8"))
'hello'
Common Mistakes
- Forgetting to convert before concatenation: Trying to join strings with numbers directly will cause a
TypeError
. - Using
str
as a variable name: This overwrites the built-instr()
function. Avoid this!
Interview Tip
When asked to serialize, log, or print object details in coding interviews, str()
is a quick and reliable tool.
Summary
str()
converts values to string format.- Useful in printing, concatenation, and formatting.
- Supports numbers, lists, dictionaries, and user-defined objects.
Practice Problem
Write a program that reads your name and age, and prints a greeting using str()
.
name = input("Enter your name: ")
age = int(input("Enter your age: "))
print("Hello " + name + "! You are " + str(age) + " years old.")