Related Articles

Related Articles

Python str() function
  • Last Updated : 15 Jul, 2020

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.

Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course.




My Personal Notes arrow_drop_up
Recommended Articles
Page :