What does {0} mean in this Python string?

2020-02-17 03:06发布

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!

6条回答
爱情/是我丢掉的垃圾
2楼-- · 2020-02-17 03:35

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

查看更多
forever°为你锁心
3楼-- · 2020-02-17 03:37

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

查看更多
神经病院院长
4楼-- · 2020-02-17 03:37

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

查看更多
5楼-- · 2020-02-17 03:37
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 .foramt(year)

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

AND Another ex:

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

查看更多
▲ chillily
6楼-- · 2020-02-17 03:44

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.

查看更多
走好不送
7楼-- · 2020-02-17 03:49

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.

查看更多
登录 后发表回答