[Tutor] Field/Variable References
spir
denis.spir at free.fr
Fri Dec 18 19:51:26 CET 2009
Serdar Tumgoren <zstumgoren at gmail.com> dixit:
> > Thank you - can you please assume that the data provided is the following:
> >
> > Columns 1 - 4 = Name (in record 1 of example = "John")
> > Column 5 = Answer1 (in record 1 of example = "9")
> > Column 6 = Answer2 (in record 1 of example = "8")
> > Column 7 = AreaCode (in record 1 of example = "762")
> >
> > Sorry - I am new to Python and trying to see if I can do data manipulation
> > in the same detail that I am used to in the SAS Data Step.
> >
>
> In the above case, the simplest solution might be to use Python's
> slicing syntax. The below solution assumes that the name can vary in
> number of characters, but that the digits for your Answers and area
> code do not vary (in other words, Answer1 and Answer2 are always a
> single digit, and AreaCode is always three digits).
>
> for line in open('my_data_file.txt'):
> name = line[0:-5] #start of line up to 5 places before end of
> string; zero-indexed with non-inclusive endpoint
> Answer1 = line[-5] #grab fifth digit from end of line
> Answer2 = line[-4] #grab fourth digit from end of line
> AreaCode = line[-3:] #grab from 3 places before end of line, through the end
> # do stuff with name, Answer1, Answer2, AreaCode
Why negative indexes when fields lengths are known?
(Reminds me of a fr. proverb: "Why do it simple when we can do it complicated?")
Denis
________________________________
la vita e estrany
http://spir.wikidot.com/
More information about the Tutor
mailing list