The str()
function converts an object into a string representation. It’s useful for displaying information, formatting text, and converting numbers or objects into readable strings.
Example
num = 42
print(str(num))
Output:
'42'
Converts the integer 42
into a string.
Syntax
str(object="")
- object (optional) → The value to convert into a string.
- Returns → A string representation of the object.
1. Converting Numbers to Strings
print(str(100)) # Output: '100'
print(str(3.14)) # Output: '3.14'
print(str(-42)) # Output: '-42'
Works with integers and floats.
2. Converting a List, Tuple, or Dictionary to a String
print(str([1, 2, 3])) # Output: '[1, 2, 3]'
print(str((4, 5, 6))) # Output: '(4, 5, 6)'
print(str({"a": 1})) # Output: "{'a': 1}"
Formats data structures as readable strings.
3. Using str()
on Booleans and None
print(str(True)) # Output: 'True'
print(str(False)) # Output: 'False'
print(str(None)) # Output: 'None'
Converts Booleans and None
into strings.
4. Custom String Representation for Objects
class Person:
def __init__(self, name):
self.name = name
def __str__(self):
return f"Person: {self.name}"
p = Person("Alice")
print(str(p)) # Output: Person: Alice
Defines a human-readable string for a class.
5. Formatting Strings with str()
age = 25
print("My age is " + str(age))
# Output: My age is 25
Needed when concatenating numbers with strings.
6. Using str()
with File Handling
data = 3.14159
with open("output.txt", "w") as file:
file.write(str(data)) # Write as text
Ensures data is saved as a string.
7. str()
vs repr()
(Human vs Debugging Format)
Function | Purpose | Example Output |
---|---|---|
str() |
User-friendly | ‘Hello\nWorld’ → Hello World |
repr() |
Debugging | ‘Hello\nWorld’ → ‘Hello\\nWorld’ |
text = "Hello\nWorld"
print(str(text)) # Output: Hello
# World
print(repr(text)) # Output: 'Hello\nWorld'
Key Notes
- ✔ Converts any object to a string.
- ✔ Used in formatting, file handling, and logging.
- ✔ Works with numbers, lists, dictionaries, and classes.
- ✔ Use
repr()
instead for debugging.
By using str()
, you can convert values into readable text, format output, and store data as strings. 🚀