Python str() Built in Function
The str() function in Python returns a string representation of an object. The syntax is:
str(object, encoding=‘utf-8’, errors=‘strict’)
where object is any Python object that can be converted to a string, encoding is the name of the encoding used to decode byte objects (default is ‘utf-8’), and errors is the type of error handling for decoding errors (default is ‘strict’).
Here are some examples of using str() with different objects:
# Use str() with numbers
num = 42
print(str(num)) # Output: '42'
# Use str() with booleans
flag = True
print(str(flag)) # Output: 'True'
# Use str() with lists
my_list = [1, 2, 3]
print(str(my_list)) # Output: '[1, 2, 3]'
# Use str() with byte objects
my_bytes = b'Hello'
print(str(my_bytes)) # Output: "b'Hello'"
print(str(my_bytes, encoding='ascii')) # Output: 'Hello'
If you have any questions about this code, you can drop a line in comment.
Comments
Post a Comment