Python String Formatting

Python has some of the very good and easy string formatters .

We will be discussing about the new format style in Python .

hello = "Hello "
world = "World "

print("{}".format(hello))             #outputs : Hello

print("{} {}".format(hello,world))    #outputs : Hello World

print("{1} {0}".format(hello,world))  #Outputs : World Hello
                                      #See the position index

Truncating strings

value = "Python is a Language"
print("{:.10}".format(value))         #Outputs : Python is

Named positions

data = {
       'x':'Hello',
       'y':'World'
}
print("{x} {y}".format(**data))        #Outputs : Hello World
    or 
print("{d['x']} {d['y']} ".format(d=data))

Date to string format

import datetime as d

today = d.datetime.now()

print(today)                #Outputs : datetime.datetime(2018, 0, 0, 0, 0, 0, 0)
                            #Datetime object
#This representation is quite not understandable . So lets quickly format it to
a string representation . 

formated = today.strftime("%B %d, %Y")  #Outputs : April 10 , 2020

Have a look at : 
https://docs.python.org/3/library/datetime.html#strftime-strptime-behavior

Leave a Reply

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