Pedro Gonçalves Pedro Gonçalves - 1 year ago 63
Python Question

how to define a function that reads tuples of strings

i wrote this code:


def key_gen(l):
lettersi = ()
for a in range(l[0], l[4]):
letters1 = lettersi + (a,)
for b in range(l[5], l[9]):
letters2 = lettersi + (b,)
for c in range(l[10], l[14]):
letters3 = lettersi + (c,)
for d in range(l[15], l[19]):
letters4 = lettersi + (d,)
for e in range(l[20], l[24]):
letters5 = lettersi + (e,)
key = letters1 + letter2+ letter3 + letters4 + letters5
return key


i run it and while im on the python shell...:

letters = ('A','B','C','D','E','F', 'G','H','I','J', ' ', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'X', 'Z', '.')


Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 3, in key_gen
TypeError: 'str' object cannot be interpreted as an integer

I dont know what mistake im making here because im a beginner in python but i want the output to be like this. Do you have any idea how to fix it?


((‘A’, ‘B’, ‘C’, ‘D’, ‘E’), (‘F’, ‘G’, ‘H’, ‘I’, ‘J’), (‘ ’, ‘L’, ‘M’, ‘N’, ‘O’), (‘P’, ‘Q’, ‘R’, ‘S’, ‘T’), (‘U’, ‘V’, ‘X’, ‘Z’, ‘.’))

maybe the function i defined cannot read tuples of strings but i dont know how to do that and ive already googled it and couldnt find anything.

Answer Source

range() expects its parameters to be of int type, and by passing l[0] you are actually passing it as char 'A'. I think what you want to do is:

for a in range(0, 4):
      letters1 = lettersi + (l[a],)

# instead of:
# for a in range(l[0], l[4]):
#       letters1 = lettersi + (a,)

There are some existing approaches to do what you are trying to achieve. Refer: How do you split a list into evenly sized chunks?. But what I would have done is not mentioned over there. My approach would have been using list slicing with lsit comprehension as:

>>> [letters[i:i+5] for i in range(0, len(letters), 5)]
[('A', 'B', 'C', 'D', 'E'), ('F', 'G', 'H', 'I', 'J'), (' ', 'L', 'M', 'N', 'O'), ('P', 'Q', 'R', 'S', 'T'), ('U', 'V', 'X', 'Z', '.')]
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download