如何在一个占位符中使用两个不同的字符串?

时间:2018-03-15 08:56:21

标签: python boolean conditional

我在课堂Re:条件语句中提出的问题上遇到了很多麻烦。

我很难理解如何让两个变量("year""s")能够进入一个{}

我必须显示一个人的年龄(已经过了他们的出生年份):

  

确定用户出生在哪一年并显示适当的年份   来自下方的消息

<FirstName>, it is now <CurrentYear>, you are <Age> year old and so you were born in <YearOfBirth>.

<FirstName>, it is now <CurrentYear>, you are <Age> years old and so you were born in <YearOfBirth>.
     

上面使用的消息必须在语法上适合年龄。

     
      
  • <FirstName>是用户的第一个名字。
  •   
  • <CurrentYear>是当年
  •   
  • <Age>是用户年数。
  •   
  • <YearOfBirth>是用户出生的年份。
  •   

以及他们给出的一些例子:

Please enter your first name: Jane
Hi Jane, please enter your age in years: 1
Jane, it is now 2018, you are 1 year old and so you were born in 2017.

Please enter your first name: Elaine
Hi Elaine, please enter your age in years: 22
Elaine, it is now 2018, you are 22 years old and so you were born in 1996.

我必须使用以下字符串:

 "{}, it is now {}, you are {} {} old and so you were born in {}."
 "year"
 "s"

2 个答案:

答案 0 :(得分:1)

你的帖子包含很多信息和隐含的问题,所以我会限制我对明确的答案:

  

我正在努力理解如何让两个变量(“年”和“s”)能够进入一个{}。

包含1 year[more than one] years的字符串就是这个:"{}, it is now {}, you are {} {} old and so you were born in {}.",它方便地包含两个格式占位符,用于数字和“年”或“年”每。选择一个最小的例子,这可能会让您了解如何解决问题:

>>> s = "you are {} {} old"
... options = [0, 1, 2, 3]
... for op in options:
...     year_label = "year"
...     if op != 1:
...         year_label += "s"
...     print(s.format(op, year_label))

打印:

you are 0 years old
you are 1 year old
you are 2 years old
you are 3 years old

可能有更多描述性的方法来写这个,我不知道它是否适合每一个可能的输入。但重要的一点是,并非输出中的每个占位符都映射到一个输入或输出变量;在这种情况下,您需要根据输入派生一个值。

答案 1 :(得分:0)

根据您需要的占位符,以下是一些代码:

import time
import sys


dashes = 1
spaces = 10
for i in range(11):
    progressbar = ['|' for x in range(dashes)]
    print("Logging In [", "|" * dashes, " " * spaces, "]", end="\r")
    dashes += 1
    spaces -= 1
    sys.stdout.flush()
    time.sleep(1)

这是你的输出:

year = 2018



name = input("Please enter your first name: ")

age = input("Hi " + name.title() + " , please enter your age in years: ")

age = int(age)

age_minus_year = (year - age)

if age != 1:

    print("{}, it is now {}, you are {}{} old and so you were born in {}.".format(name.title(), year, age, ' years', str(age_minus_year)))

else:

    print("{}, it is now {}, you are {}{} old and so you were born in {}.".format(name.title(), year, age, ' year', str(age_minus_year)))

根据您提到的所需代码,此代码应为您提供所需的格式。你只需要在这里使用.format方法。 if语句将简单地确定print语句是否应该根据用户输入的内容来说明年份或年份。