Remember
str() produces a human-readable string representation of an object.
str() produces a human-readable string representation of an object.
Follow the example, change its sample, and compare what happens.
Explain the result and test your understanding.
Focus on how the names, objects, and calculations change. We’ll inspect the printed output in the next section.
Follow the code and watch its state change. Guided simulation.
number = 3
text = str(number)
print(text)
print(type(text).__name__)Top-level scope
3Object 2 · str'3'str() produces a human-readable string representation of an object.
(no output)
What do you expect this program to print?
EXAMPLE INSTRUCTIONS
number = 3
text = str(number)
print(text)
print(type(text).__name__)
|
v
DISPLAYED RESULT
3
str
FINAL BINDINGS
number --> object 1 (int)
text --> object 2 (str)
object 1: 3
object 2: '3'Choose a different sample input, then follow every step through to the output. Before revealing it, predict what the program will display.
Choose a sample and follow its execution. Guided simulation.
number = 3
text = str(number)
print(text)
print(type(text).__name__)Top-level scope
3Object 2 · str'3'The example has finished. Compare the final output with the values and references above.
3 str
What do you expect this program to print?
number = 3
text = str(number)
print(text)
print(type(text).__name__)str() FunctionThe 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.
str(object='', encoding='utf-8', errors='strict')
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.x = 123
print(str(x))
'123'
my_list = [1, 2, 3]
print(str(my_list))
'[1, 2, 3]'
pi = 3.14159
print(str(pi))
'3.14159'
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
b = b"hello"
print(str(b, encoding="utf-8"))
'hello'
TypeError.str as a variable name: This overwrites the built-in str() function. Avoid this!When asked to serialize, log, or print object details in coding interviews, str() is a quick and reliable tool.
str() converts values to string format.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.")
Connect what you noticed in the example with the idea below.
str() produces a human-readable string representation of an object.
str() modifies the source object’s type in place.
This is the misconception to avoid.Reference checks are optional and do not count toward course progress.