我试图在冒号前后找到输入用户的整数值。我已经弄明白了如何检索第一个值,但如果冒号后面的值超过一个字符,它只会抓取第一个值。
startingWeight = input(("Starting weight of food (in lbs:ozs)="))
endingWeight = input(("Ending weight of food (in lbs:ozs="))
startingWeightPos = startingWeight.find(":")
endingWeightPos = endingWeight.find(":")
startingWeightPounds = startingWeight[0:startingWeightPos]
startingWeightOz = startingWeight[1:startingWeightPos]
endingWeightPounds = endingWeight[0:endingWeightPos]
endingWeightOz = endingWeight[1:endingWeightPos]
print (startingWeightPounds)
print (endingWeightPounds)
print (startingWeightOz)
print (endingWeightOz)
答案 0 :(得分:0)
使用split
获取:
左侧和右侧的内容。
text = '100:66'
text_split = text.split(":")
lbs = text_split[0]
ozs = text_split[1]
如果需要,可以使用float()
将它们转换为浮动。
答案 1 :(得分:0)
如果您想使用切片,则两个切片为[:pos]
(一切最高为pos
),[pos+1:]
(pos
之后的所有内容)。
E.g。
pos = pounds.index(':')
pounds = weight[:pos]
oz = weight[pos+1:]
但split
函数的存在使这更简单。
pounds, oz = weight.split(':')