Python str() function is used to convert an object to its string representation. It is a built-in function that can be used to convert objects of different data types, such as integers, and floats.
Example:
In the given example, we assign an integer value to a variable and convert that integer variable to the string variable and print it in Python.
Python3
val=10
val_str= str(val)
print(val_str)
|
Output:
10
Python str() Function Syntax
Syntax: str(object, encoding=’utf-8?, errors=’strict’)
Parameters:
- object: The object whose string representation is to be returned.
- encoding: Encoding of the given object.
- errors: Response when decoding fails.
Returns: String version of the given object
str() function in Python Example
Demonstration of str() function
In the given example, we are using str() on an empty string and string.
Python3
s = str()
print(s)
s = str("GFG")
print(s)
|
Output:
GFG
Convert an Integer/Float to a String in Python
In the given code, we are converting integer and float to the string type with str() in Python. For more
Python3
num = 100
s = str(num)
print(s, type(s))
num = 100.1
s = str(num)
print(s, type(s))
|
Output:
100 <class 'str'>
100.1 <class 'str'>
Convert Bytes to a String in Python
In the first example, the errors=’replace’ argument is used. When we are founding abnormal characters in the string, it replaces them with the ‘?’ character. In the second example, the errors=’backslashreplace’ argument is used. It replaces abnormal characters in a string with backslash escapes. In the third example, the errors=’xmlcharrefreplace’ argument is used. It replaces abnormal characters in a string with XML character references.
Python3
b = bytes('Café', encoding='utf-8')
print(str(b, encoding='ascii', errors='replace'))
print(str(b, encoding='ascii', errors='backslashreplace'))
|
Output :
Caf��
Caf\xc3\xa9
Exceptions of str() in Python
There are six types of error taken by this function.
- strict (default): it raises a UnicodeDecodeError.
- ignore: It ignores the unencodable Unicode
- replace: It replaces the unencodable Unicode with a question mark
- xmlcharrefreplace: It inserts XML character reference instead of the unencodable Unicode
- backslashreplace: inserts a \uNNNN Espace sequence instead of an unencodable Unicode
- namereplace: inserts a \N{…} escape sequence instead of an unencodable Unicode
Example:
Python3
a = bytes("ŽString", encoding = 'utf-8')
s = str(a, encoding = "ascii", errors ="ignore")
print(s)
|
Output:
String
In the above example, the character Ž should raise an error as it cannot be decoded by ASCII. But it is ignored because the errors are set as ignore.
Last Updated :
20 Jun, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...