Python str() function

The str() function of Python returns the string version of the object.

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

Example 1:



Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python program to demonstrate
# strings
  
# Empty string
s = str()
print(s)
  
# String with values
s = str("GFG")
print(s)

chevron_right


Output:

GFG

Example 2: Converting to string

Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python program to demonstrate 
# strings
  
num = 100
s = str(num)
print(s, type(s))
  
num = 100.1
s = str(num)
print(s, type(s))

chevron_right


Output:

100 <class 'str'>
100.1 <class 'str'>

Errors in String

There are six types of error taken by this function.

  • strict (default): it raises a UnicodeDecodeError.
  • ignore: It ignores the unencodable Unicodet
  • replace: It replaces the unencodable Unicode to a question mark
  • xmlcharrefreplace: It inserts XML character reference instead of the unencodable Unicode
  • backslashreplace: inserts a \uNNNN espace sequence instead of unencodable Unicode
  • namereplace: inserts a \N{…} escape sequence instead of unencodable Unicode

Example:

Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python program to demonstrate
# str()
  
a = bytes("ŽString", encoding = 'utf-8')
s = str(a, encoding = "ascii", errors ="ignore")
print(s)

chevron_right


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 is set as ignore.




My Personal Notes arrow_drop_up


If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.