What does {0} mean in this Python string?

Each Answer to this Q is separated by one/two green lines.

The following program uses {0} in a string, and I’m not sure how it works, it came up in an online tutorial about iteration for Python, and I can’t seem to find anywhere explaining it.

import random

number = random.randint(1, 1000)
guesses = 0

print("I'm thinking of a number between 1 and 1000.")

while True:
   guess = int(input("\nWhat do you think it is? "))
   guesses += 1

    if guess > number:
        print("{0} is too high.".format(guess))
    elif guess < number: 
        print("{0} is too low.".format(guess))
    else:
        break

print("\nCongratulations, you got it in {0} guesses!\n".format(guesses))

Thank you!

It’s an indicator to the format method that you want it to be replaced by the first (index zero) parameter of format. (eg "2 + 2 = {0}".format(4))

It’s a boon for placing same arg multiple times

print("When you multiply {0} and {1} or {0} and {2}, the result is {0}".format(0,1,2))

Isn’t this nice!!!

http://docs.python.org/release/3.1.3/library/stdtypes.html#str.format

Perform a string formatting operation. The format_string argument can
contain literal text or replacement fields delimited by braces {}.
Each replacement field contains either the numeric index of a
positional argument, or the name of a keyword argument. Returns a copy
of format_string where each replacement field is replaced with the
string value of the corresponding argument.

It’s a placeholder which will be replaced with the first argument to format in the result. {1} would be the second argument and so on.

See Format String Syntax for details.

That is the new python formatting style. Read up on it here.

year = int(input("Enter the year: "))
if year%4 == 0:
    if year%100 == 0:
        if year%400 == 0:
            print("{0} Year is Leap Year".format(year))
        else:
            print("{0} Year is Not Leap Year".format(year))
    else:
        print("{0} Year is Leap Year".format(year))
else:
    print("{0} Year is Not Leap Year".format(year))

here I can place the year argument in multiple lines using .format(year)

output :

> Enter the year: 1996
> 1996 Year is Leap Year

AND Another example:

name="sagar"
place="hyd"
greet="Good"
print("my name is {0}. I am from {1}. Hope everyone doing {2}".format(name,place,greet))

output:

> my name is sagar.
> I am from hyd. Hope everyone doing Good

OR

print("my name is {0}. I am from {1}. Hope everyone doing {2}".format('Sagar','Hyd','Good'))

Output:

> my name is sagar. I am from hyd. Hope everyone doing Good


The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 .