Sunday, August 2, 2020

Python String formatting


                                       Python String formatting

                                             

  Formatting string in python can be achieved via different ways as below.


Declaring variables :


greeting = 'Hello'

name = 'Abizer'

morninggreeting = 'Morning !'



Concatenating string (Default and easy when not many strings need to be Concatenated)


message =  greeting + ", " + name + "." + morninggreeting

Formatting strings via below method to make it more readable.



message =  '{}, {}.{}'.format(greeting, name, morninggreeting)


If your using 3.6+ version of Python we can use f strings to achieve same thing


message = f'{greeting}, {name}.{morninggreeting}'





Finally print the output.


print(message)

Output :

Hello, Abizer.Morning !


No comments:

Post a Comment