2

I have a string encryption algorithm which converts a inputted string into list of string . The output is supposed to be the first letter of every list element(string here). example in the list1 below

output is supposed to be 'tir hsy ia st' and list2 output should be 'tir hsy iat sto'

But with the code i'm having it is able to print the output only if every list element(string here) contains same number of letters otherwise(in case of list 1) it raises "string index out of range".

The ceil here indicates the number of letters in each list element.(4 here in this case)

How do i go about printing the output of list1 in the way shown? p.s-i'm beginner in python

list1=['this','isat','ry']

list2=['this','isat','ryto']

my code to print the output

for elem in range(ceil):
        for i in range(len(list1)):
            if list1[elem][i]:
                print(list1[i][elem],end='')
        print(end=' ')
2
  • It's not clear how to arrive at the expected output. Should not one of the expected characters be a? Commented Feb 14, 2019 at 18:06
  • yeah right..nice observation Commented Feb 14, 2019 at 18:08

3 Answers 3

2

I guess you expect if list[elem][i] to be false if i is not a member of list[elem] but that's not what it does. Rather, Python tries to check if the value is truthy or not, and when there isn't a value there at all, you get in IndexError.

Anyway, rather than look before you leap, you could just ask for forgiveness instead of permission:

list1=['this','isat','ry']

for elem in range(len(list1[0])):
        for i in range(len(list1)):
            try:
                print(list1[i][elem],end='')
            except IndexError:
                continue
        print(end=' ')

If you prefer the "look before you leap" variant, the proper way to check if the index is there is

            if i in list1[elem]:

I assumed the first element of the list will always have the maximum length, so we simply loop over that in the outer loop.

Sign up to request clarification or add additional context in comments.

Comments

1

All you were missing really is a check to see if your element is long enough to avoid the value error. I also added inline code to generate what i assume your ceil was.

for i in range(max([len(i) for i in list1])):
   for j in list1:
     if i < len(j):
       print(j[i], end='')
   print(end=' ')

Comments

1

You can use itertools.zip_longest instead:

from itertools import zip_longest
print(' '.join(map(''.join, zip_longest(*list1, fillvalue=''))))

This outputs:

tir hsy ia st

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.