Python str() Function



The Python str() function is used to convert the given value into a string. A string is a sequence of characters that is used to represent text. A character can be any individual letter, number, symbol, or whitespace.

In Python, you can create a string by enclosing a sequence of characters within single quotes (' ') or double quotes (" ").

Syntax

Following is the syntax of Python str() function −

str(x)

Parameters

This function takes a value 'x' as a parameter that you want to convert into a string.

Return Value

This function returns a string object.

Example

In the following example, we are using the str() function to convert the integer "42" into a string −

num = 42
str_num = str(num)
print('The string value obtained is:',str_num)

Output

Following is the output of the above code −

The string value obtained is: 42

Example

Here, we are using the str() function to convert the floating-point number "3.14" into a string −

float_num = 3.14
str_float = str(float_num)
print('The string value obtained is:',str_float)

Output

Output of the above code is as follows −

The string value obtained is: 3.14

Example

In here, we are converting the boolean value "True" into its string representation using the str() function −

boolean_value = True
str_boolean = str(boolean_value)
print('The string value obtained is:',str_boolean)

Output

The result obtained is as shown below −

The string value obtained is: True

Example

In this case, the str() function converts the list "[1, 2, 3]" into a string representation −

my_list = [1, 2, 3]
str_list = str(my_list)
print('The string value obtained is:',str_list)

Output

Following is the output of the above code −

The string value obtained is: [1, 2, 3]

Example

Finally, we are using the str() function to convert the complex number "(2+3j)" into its string representation −

complex_num = complex(2, 3)
str_complex = str(complex_num)
print('The string value obtained is:',str_complex)

Output

The result produced is as follows −

The string value obtained is: (2+3j)
python-str-function.htm
Advertisements