[Tutor] Change a text string from a list and change it into an integer number.(WinXP/py2.6.2/Beginner)
Dave Angel
davea at ieee.org
Fri Nov 6 14:28:45 CET 2009
Alan Gauld wrote:
> <div class="moz-text-flowed" style="font-family: -moz-fixed">
> "Katt" <the_only_katala at verizon.net> wrote
>
>> date = "cyear_11_05"
>> date2 = date.split("_")
>> check_year = date2[0]
>> if check_year == "cyear":
>> year = localtime().tm_year
>> else:
>> year = int(date2[0])
>> print year
>>
>> Did I do the slice incorrectly? I thought that when you take the
>> first location (0) of a list then it would take the "cyear" in stead
>> of just the "c".
>
> When debugging this kind of thing insert some print statements
> to check what date2 and check_year really look like. Or try using
> the >>> prompt to experiment until you are happy with the behaviour
> of the function with differernt sample data.
>
> HTH,
>
>
Several things I'd add.
1) You forgot to include the line
from time import localtime
2) You don't specify the python version or OS environment you're running
on (though I don't think it matters here)
3) The example "works" as it is, meaning the localtime() function is
called, and year is set to 2009 (when I run it today with CPython
2.6.2) So I'm guessing you retyped the example into your message.
Always use copy/paste, and if practical, show the printed output results
you got, or the error/traceback if it got an error.
4) You use the word "slice" in your query, but there are no slices in
the program. The line that binds check_year has a "subscript"
operation, which is similar to a slice, but not the same. The syntax is
different, in that there's no colon in the square brackets. And of
course the meaning is different.
If I had to guess, I'd say that somewhere in your real code, you have a
second subscript going on. If you use a subscript on a list of strings,
you get a string. If you use a subscript on that, you get another
string, consisting of a single character.
So if
date2 == ["cyear", "11", "05"]
date2[0] == "cyear"
date2[0][0] == "c"
DaveA
More information about the Tutor
mailing list