str() function in Python is a built-in Function that converts the specified value or object into a string.
This function returns a String nicely printable representation of the specified object.
The general syntax of str() function is as follows:
str(object)
This function returns a string representation of the object. If we do not provide any object, it returns an empty string.
Python str() Function Example Program
Example 1:
# Python program to convert integer number into a string. num = 50 create_string = str(num) print(create_string, type(create_string)) # Concatenating two strings using + operator after conversion. concatenated_string = create_string + "Hello" print(concatenated_string)
Output: 5050Hello
In this example, we have assigned a value 50 to the variable named num. Then, we have called str() function and passed the value of num into it to convert the integer number into a string.
We have stored the returned string into a variable named create_string and displayed it on the console. Then, we have joined two strings using + sign operator to form a new string and stored into a variable named concatenated_string, and displayed it.
Example 2:
# Python program to convert float number into a string. num = 50.567 create_string = str(num) print(create_string, type(create_string)) # Joining three strings using + operator after conversion. concatenated_string = "Hi" + create_string + "Hello" print(concatenated_string) # Concatenating float number and a string. con_str = num + "Hi" print(con_str)
Output: 50.567Hi50.567Hello con_str = num + "Hi" TypeError: unsupported operand type(s) for +: 'float' and 'str'
Example 3:
# Python program to create an empty string. create_string = str() print(create_string,type(create_string))
Output:
In this example, we have not passed any value to the str() function. Therefore, it will return an empty string of type str.
In this tutorial, you have known about str() built-in function provided by Python with some useful examples. Hope that you will have understood all the basic points of str() function and practiced all example programs.
Thanks for reading!!!
The post Python str() Function with Example appeared first on Scientech Easy.