What Does {0} Mean in This Python String?

What Does {0} Mean in This Python String?

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!

0

6 Answers

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))

0

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!!!

1

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.

2

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Sarah Jenkins
Author

Sarah Jenkins

Sarah Jenkins is a veteran tech journalist with over 12 years of experience covering artificial intelligence, mobile innovations, and digital ethics. Her insights have appeared in leading technology publications worldwide.