Question

I am working from a Mac and have a question about a python for look. I am using a .txt file called rectangle.txt and inside the file it looks like this:

abcde
fghij
klmno

I need to read these in using stdin. But this is what I need my program to:

afk
bgl
chm
din
ejo

So far, I have a program that reads all the lines and splits them and prints them out. CODE EDITED

So when I changed my code to this:

for line in sys.stdin.readline():
    ls1 = line
    print ls1

I received the list:

a
b
c
d
e

So now I just need to loop through those other ones, but I can't figure that out

I am running this function from the command line:

python rectangle.py < rectangle.txt

I am trying to learn all of this, so instead of giving me the answer, I would like someone to help explain this to me, in a way hopefully I can understand.

Also, in addition to this .txt file input. My program will also be test with these inputs:

123
456
789

and

A
B
C

All doing the same thing as above. Thank you again in advance for helping me. I have been working on this for hours and can't seem to figure it out.

Was it helpful?

Solution

I'm assuming the input in each line has to be the same length.

In this case have a list of the input strings and for the length of one of these strings loop.

["abcde", "fghij", "kilmn"] from here here what do you notice about the pattern of the first character from each string? "a" + "f" + "k".

OTHER TIPS

The trustworthy zip function comes to help:

>>> lines = ["abc", "def", "ghi"]
>>> result = [''.join(x) for x in zip(*lines)]
>>> result
['adg', 'beh', 'cfi']

Explanation: zip does exactly what you'd expect from it - aggregating an element from each given iterable into a new list. We have to pass zip the iterables separately and not as a list which is what *lines does. In the end we just join the single character array together because we want an array of strings and not an array of an array of characters.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top