[Tutor] Python = {0}.format
Alan Gauld
alan.gauld at btinternet.com
Mon Aug 18 00:41:43 CEST 2014
On 17/08/14 15:50, abid saied wrote:
> Hi,
>
> I’m in the process of teaching myself python. Can someone have a look at
> the text in red and explain please.
> print("This program displays a given quote in different formats")
> print() # Why is this needed?
Its not it only adds a bnlank line. You could achieve the same result by
adding a \n character at the end of the last line.
> quote = input("Please enter a quote to format: ")
> print(quote)
> replaceWord = input("Which word in the quote would you like to replace: ")
> replaceWith = input("Please enter the word to replace with: ")
> print("The original quote is: {0}".format(quote))
> # Not sure what the {0}.format is doing
String formatting inserts data values into a string.
Notice that the .format() occurs after the striong,
not after the {} marker.
The {} marks the place where the data will be inserted.
The 0 indicates that its the zero'th (or first) item in
the list that should be inserted. The list of data items
is the list of parameters to format(). Here is an example:
print ("{0} x {1} = {2}".format(3,4,12)
And another showing the value of the indexing:
s = "{0} can be written as {0} or {1}".format('four',4)
print(s)
You can have various other codes inside the {} to control
spacing and justification or padding etc.
Here is the official documentation page on the subject:
https://docs.python.org/3/library/string.html#string-formatting
HTH
--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.flickr.com/photos/alangauldphotos
More information about the Tutor
mailing list