0
name = input("Please enter your name: ")
age= int(input("How old are you,{0}?" .format(name)))

print(age)

if age >= 22:
    print(f"Congratulations {name} , You're eligible to vote.")
else:
    print(f"Oops {name} ,We're are sorry but you can try again in {0} years." .format(22 - age))

The outcome is not minusing the .format command? can we not use both the functions into one line of code.

0

2 Answers 2

3

The f string is evaluated to a str which has the format method, so yes, it will work. The trick is that you have to escape the brackets intended for the format method so that they resolve properly later.

>>> foo = "bar"
>>> f"foo {foo} 0 {{0}}".format("baz")
'foo bar 0 baz'

Notice that {{0}} resolves to {0} in the f string and then to the first formatted parameter.

Sign up to request clarification or add additional context in comments.

Comments

0

This makes no sense at all, you can do everything with f-strings:

name = input("Please enter your name: ")
age = int(input(f"How old are you {name}? "))
print(age)
if age >= 22:
    print(f"Congratulations {name}, You're eligible to vote.")
else:
    print(f"Oops {name}, We're are sorry but you can try again in {22 - age} years.")

f-strings are now the best option. For more info see: https://peps.python.org/pep-0498/#abstract

1 Comment

While you're not wrong, per se, this does not actually answer the question and belongs in a comment instead.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.