Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (16.4k points)

In the following code, {0} is been used in a string and I'm not sure about it and how it works. I can't able to find it anywhere to 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))

2 Answers

0 votes
by (26.4k points)
edited by

It acts as an indicator in the format method that if you want it to be replaced by the first parameter(index zero) of format.

Example : 

print(42+261={0}.format(303))

Here, {0} will be replaced by 303.  

If you want to learn more about Python? Come & Join: python course 

0 votes
by (3.1k points)

{0} serves as a placeholder for string formatting in Python. It indicates where the first argument will be inserted when using the format() method. You can use multiple placeholders like {1}, {2}, and so on for additional arguments.

Example: 

employee_name = “Satvik”

employee_salary = 20000

formated_string =  “Employee Name is {0} and salary is {1}”.format(employee_name,employee_salary)

print(formated_String)

Output: 

Employee Name is Satvik and salary is 20000

In the above example, name will replace {0} and age will replace {1}. Using this procedure, dynamic strings can be created.

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
asked Feb 7, 2021 in Python by laddulakshana (16.4k points)
0 votes
5 answers
0 votes
1 answer

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...