Write A Python Script To Create A String In 3 Different Possible Ways

Hi in this article you will learn the  three  two ways to create a string in the Python program.

These methods can be used to create a string  and use them.

 

 

Write A Python Script To Create A String In 3 Different Possible Ways

 



Write A Python Script To Create A String In 3 Different Possible Ways

The very first method is using str() function. Just provide any data type as an input argument to the string function and this will create the string type of any data type as shown below.

I will be taking first_str a variable containing a list of items then use str() function to create a string and storing it into a variable named as first and then printing the type of of first variable this will create the list to string type

first_str = [1, 5, 6, 8]
first = str(first_str)
print(type(first))





Second method using format()  function call,  format function is the function that will create all the given  input arguments to it into a string as shown below.  I'll be  using  an integer as an input to the format function.

Take a variable named as second_format And assign an integer 89 to it and then using the format function create a string type of given integer data type and then print the variable type second. This is the second method to create a string.

second_format = 89
second = '{0}'.format(second_format)
print(type(second))




The third method is using %s this will create a string type of any given data type, Take a variable named as third underscore Legacy and assign 42 it and then use the percentage to create a string and create a new string named as third and print the type of third.

This is the third method to create a string.

third_legacy = 42
third = '%s' % third_legacy
print(type(third))



Complete Code
=================

first_str = [1, 5, 6, 8]
first = str(first_str)
print(type(first))

second_format = 89
second = '{0}'.format(second_format)
print(type(second))

third_legacy = 42
third = '%s' % third_legacy
print(type(third))



Output
==========
<class 'str'>
<class 'str'>
<class 'str'>



Conclusion
===============
Try modifying the above Python program by providing the input with the different data types and try to create a string out of those data types using str(), format() and percentage %.

Comment down below if you have any suggestions  to improve the above python




Post a Comment

0 Comments