Gary Herron
1/26/2008 5:53:00 PM
JAMoore84@gmail.com wrote:
> Hi all,
>
> I am trying to write a simple program that will accept an integral
> "time" input in the HHMMSS format and output a "HH:MM:SS" form. My
> code is as follows:
> ========================
> import string
>
> def FormatTime(time):
> '''Converts an HHMMSS string to HH:MM:SS format.'''
>
> timeString = str(time) #converts the num to string
>
> hours = [timeString[0], timeString[1]]
> minutes = [timeString[2], timeString[3]]
> seconds = [timeString[4], timeString[5]]
>
> Ftime = "%s:%s:%s",(hours,minutes,seconds)
> clock = Ftime.join()
>
> return clock
> ===========================
>
> when I run it from IDLE, I get this:
>
>
>>>> Format.FormatTime(time)
>>>>
> ['1', '1', ':', '2', '2', ':', '3', '3']
> ['1', '1', ':', '2', '2', ':', '3', '3']
>
The code you posted did not produce the output you are showing. You'll
have to be more careful with your posting if you expect to get a useful
answer.
Beyond that, there are a bundle of errors in the code that will prevent
it from working:
If you want to carve a string into substrings, use this kind of syntax
hours = timeString[0:2]
minutes = timeString[2:4]
seconds = timeString{4:6]
If you want to combine small strings into longer strings you've got
several choices:
output = hours + ':' + ...
or
output = "%s:%s:%s" % (hours, ...) #NOTICE the % operator between
the format string and value tuple
Since both of those produce a string as output, you have no need of a
join, BUT if you do decide to produce a list of strings that you want to
join into a longer string, you need to use join correctly:
parts = [hours,minutes,seconds]
output = ':'.join(parts)
Another error: If your time starts with an hour that is just a single
digit, then your string will be only 5 digits long (there will be no
leading zero). In that case, all the extraction of individual fields
based on indexing into the string will be off by one.
> My questions-
> 1) Why is this function printing out twice?
>
Show us your real code.
> 2)It may be a formatting issue, but I want to have the output as
> "HH:MM:SS", rather than having it broken out into each cell. I
> thought the 'join' command would do this, but I must not be using it
> properly/understanding something.
>
See the example above.
> 3)as a side note, I've noticed that the parameter "time" passed in
> must be passed in as a string, otherwise I receive an error that
> "time" is unsubscriptable. Am I unable to pass in an int and then
> convert it to a string within the function with str()?
>
Of course you can pass any type into a function. Then you have to write
the program to operate correctly on whatever the input type is.
> I've been at this for a while, so I may not be able to see the forest
> through the trees at this point. I'd greatly appreciate any
> suggestions or instruction on these mistakes.
>
My guess is that's why the code you show does not match the output you
present.
> Best,
>
> Jimmy
>
Gary Herron