Python str() Function – Tutorial with Examples

The str() function in Python is a built-in function that is used to convert various data types into a string representation. The str() function is used to convert any data type into a string format, so that it can be used for string manipulation or to be printed out as a human-readable string.

Syntax

str(object)

Parameters

  • object : The object that needs to be converted to a string. This can be any data type such as an integer, float, list, dictionary, etc.

Return Value

The str() function returns a string representation of the input object. If the object passed to the function is not a valid data type that can be converted to a string, a TypeError will be raised.

Examples

Example 1: Converting integer to string

# Converting integer to string
x = 42
print(str(x))

Output

42

Example 2: Converting float to string

# Converting float to string
y = 3.14
print(str(y))

Output

3.14

Example 3: Converting a list to string

# Converting a list to string
z = [1, 2, 3]
print(str(z))

Output

[1, 2, 3]

Use Cases

The str() function has several use cases, including:

  • Converting numeric data types into a human-readable string format for display or printing purposes.
  • Converting data structures like lists, dictionaries, and sets into string representations so they can be manipulated as strings and written to files or used in network communication.
  • Converting user inputs such as numbers entered by the user into strings for string manipulation and processing.
  • Converting values from APIs, databases, or other sources into a string format for further processing.

In conclusion, the str() function is an essential tool in Python for converting different data types into a string representation and is commonly used in many applications and scenarios in the world of programming and software development.

Leave a Reply

Your email address will not be published. Required fields are marked *