【问题标题】:Using find function in Python在 Python 中使用 find 函数
【发布时间】:2014-10-06 00:59:21
【问题描述】:

我想用 find 功能解决这个问题。我一直在使用 split 函数来处理它,因为我不明白 find 。如果有人能告诉我如何用 find 来做,那就太棒了。我也陷入了这部分问题。

start = ("Please enter the starting weight of food (in lbs:ozs) = ")
answerOne = input(start).strip()
startPounds, startOunces = answerOne.split(":")
startPounds = int(startPounds)
startOunces = int(startOunces)
end = "Please enter the ending weight of food (in lbs:ozs) = "
answerTwo = input(end).strip()
endPounds, endOunces = answerTwo.split(":")
endPounds = int(endPounds)
endOunces = int(endOunces)
startPoundsO = startPounds * 16
endPoundsO = endPounds * 16
poundsO = startPoundsO - endPoundsO

这是我遇到问题的地方。

这是原来的问题。

一只猴子正在被喂一些食物。阅读以磅为单位的起始重量:盎司。还要以 lbs:ozs 为单位读取最终重量(您可以假设这小于起始重量。找出差异并打印出猴子以 lbs:ozs 为单位消耗的食物量。

这是提供的数据。

食物起始重量(磅:盎司)=8:9

食物的最终重量(磅:盎司)=6:14

猴子消耗的食物 (lbs:ozs)=1:11

【问题讨论】:

  • split 非常适合这个。为此使用find 就像使用剪线钳准备生菜一样。你可以做到,但很尴尬。

标签: python python-3.x split find


【解决方案1】:

同意@Amadan,有点尴尬:

startPounds, endsPounds = int(answer[0:answer.find(':')]), int(answer[answer.find(':')+1:len(answer)])

【讨论】:

  • 终于让一切正常工作,但我的输出有什么问题,无法正确打印。打印(磅),“:”,(盎司)
  • 打印(磅),“:”,(盎司)
  • 您可以使用print("Result = %d:%d" % (pounds, ounces)) 进行输出
  • 我认为最好使用格式而不是 %。
  • @TonySuffolk66 谢谢,我没有注意到 OP 放了 python-3.x 标签。 @CharlesTaylor 请修改为print("Result = {0}:{1}".format(pounds, ounces)) 并作为参考python way of printing: With 'format' or percent form?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-02-18
  • 1970-01-01
  • 2014-11-18
  • 1970-01-01
  • 2011-08-22
  • 2015-11-09
相关资源
最近更新 更多