在python中拆分整数

2024-10-03 19:28:49 发布

您现在位置:Python中文网/ 问答频道 /正文

我对python还很陌生,正在尝试根据“思考python”中的练习构建一个运行10公里的计算器

我要做的是把输入时间分解成两个独立的数字,即:43.12。。。 然后执行(43x60)-给出秒数,然后加上剩余的秒数+12。。 给出准确的数字。。你知道吗

下面是运行它,如果我硬编码4312作为一个整数-但我想接受它的动态。。。有人能帮我指出正确的方向吗

#python 10k calculator

import time

distance = 6.211180124223602
time = float(input("what was your time?"))
tenK = 10
mile = 1.61
minute = 60
sph = 0

def convertToMiles():
    global distance
    distance = tenK / mile
convertToMiles()
print("Distance equal to :",distance)


def splitInput():
    test = [int(char) for char in str(4312)]
    print(test)
splitInput()

Tags: testtimedef时间数字计算器distanceprint
3条回答

当您在输入中请求数字时,您已经在将其转换为浮点数了;只需将其作为字符串接受,然后就可以轻松地将其分成不同的部分:

user_input = input('what was your time?')
bits = user_input.split('.') # now bits[0] is the minute part,
                             # and bits[1] (if it exists) is
                             # the seconds part
minutes = int(bits[0])
seconds = 0
if len(bits) == 2:
    seconds = int(bits[1])

total_seconds = minute*60+seconds

我会让用户以[hh:]mm:ss格式输入一个字符串,然后使用如下命令:

instr = raw_input('Enter your time: [hh:]mm:ss')
fields = instr.split(':')
time = 0.0
for field in fields:
   yourtime *= 60
   yourtime += int(field)
print("Time in seconds", yourtime)

但如果你真的需要时间的话时间.strtime(). 你知道吗

如果不立即调用convert将用户输入转换为float,则更容易。字符串提供了split函数,而浮点函数则没有

>>> time = input("what was your time? ")
what was your time? 42.12
>>> time= time.split('.')
>>> time
['42', '12']
>>> time= int(time[0])*60+int(time[1])
>>> time
2532

相关问题 更多 >