开发者

Subtracting "variable[#]" with two digits in python?

I'm building a script in python to calculate the amount of time in between hours entered by a user Lets say for example I did the following

time = input("Enter times:")

and the user entered 3,11 to show that the start time was three, and the end time was 11. Therefore, time would equal 3,11. I want to be able to subtract this to show that there is an开发者_开发技巧 8 hour difference

I tried using

timesub= (int(time[3])-int(time[1])) 

but it gives me -2 because time[3] is equal to 1. How do I make it use 11 instead of 1?


time_input = raw_input("Enter times:")
time_parts = time.split(',')
time_diff = int(time_parts[1]) - int(time_parts[0])


You can use the split method to split a string and assign the individual values to separate variables:

start, end = time.split(',')
timesub = int(end) - int(start)

If you want to get extra fancy you could apply the int function at the same time:

start, end = [int(t) for t in time.split(',')]
# or
start, end = map(int, time.split(','))

timesub = end - start
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜