从输入中提取某些数据

时间:2014-10-03 19:21:22

标签: python python-3.x input extract

我试图从第一行提取输入的某个部分并用它来计算问题,然后将它重新组合在一起。

例如,

Please enter the starting weight of food in pounds followed by ounces:8:9

Please enter the ending weight of food in pounds followed by ounces:6:14

我想先提取体重并开始工作,还是我看错了?这是问题描述:

编写伪代码和Python 3.3程序以解决以下问题。一只猴子正在吃一些食物。以lbs:ozs读入起始重量。同时读取lbs:ozs的结束重量(你可以假设它小于起始重量。找出差异并打印出猴子消耗的食物量,单位为lbs:ozs。下面显示了一些样本数据(带有相应的输出)。

提示:首先将所有值转换为盎司。使用“find”命令在输入数据中找到“:”(参见Y上的sample2)。

生成#1 : >

  
Starting weight of food (in lbs:ozs)=8:9

Ending weight of food (in lbs:ozs)=6:14

Food consumed by the monkey (lbs:ozs)=1:11

2 个答案:

答案 0 :(得分:0)

试试这个:

msg = 'Starting weight of food (in lbs:ozs) = '
answer = input(msg).strip()
try:
    pounds, ounces = answer.split(':')
    pounds = float(pounds)
    ounces = float(ounces)
except (ValueError) as err:
    print('Wrong values: ', err)

print(pounds, ounces)

答案 1 :(得分:0)

# get input from the user, e.g. '8:9'
start_weight= input('Starting weight of food (in lbs:ozs)=')
# so start_weight now has the value '8:9'

# find the position of the ':' character in the user input, as requested in the assignment: 'Use the “find” command to locate the “:” in the input data'
sep= start_weight.find(':')
# with the input from before ('8:9'), sep is now 1

# convert the text up to the ":" character to a number
start_pounds= float(start_weight[:pos])
# start_pounds is now 8

# convert the text after the ":" character to a number
end_pounds= float(start_weight[pos+1:])
# end_pounds is now 9

# get input from the user, e.g. '6:14'
end_weight= input('Ending weight of food (in lbs:ozs)=')

SNIP # You'll have to figure this part out for yourself, I can't do the entire assignment for you...

# finally, display the result, using "str(number)" to convert numbers to text
print('Food consumed by the monkey (lbs:ozs)=' + str(pounds_eaten_by_monkey) + ':' + str(ounces_eaten_by_monkey))

这应该让你开始。剩下的就是编写将磅和盎司转换成磅的代码,并计算猴子消耗的食物量。祝你好运。