goblin_rocket goblin_rocket -4 years ago 90
Python Question

Are these list items strings or not?

Edit: With the feedback from the community and re-reading the docs for enumerate I realise now that I am returning an index and value and not two values so it makes sense for 'i' to be an int.

I had this string:

line1 ='ewtloYgcFQaJNhHVGxXDiQmzjfcpYbzxlWrVcqsmUbCunkfxZWDZjUZMiGqhRRiUvGmYmvnJIH EmbT'


which I changed into a list:

line1_list = list(line1)


I then wanted to check for lower and upper case characters next to each other like this:

for i, j in enumerate(line1_list[:-1]):
if i.islower() and j.isupper():
print(i,j)


this returns an error:

AttributeError: 'int' object has no attribute 'islower'


I didnt understand why it was saying the items in the list were ints so then I did this:

>>> type(line1_list[0])
<type 'str'>
>>> type(line1_list[0]) == str()
False


I am confused....

Answer Source

when iterated upon, enumerate returns a tuple (index,value) of your collection, so obviously some confusion here.

Another nice way to do that without indexes is with zip and slicing, and covers the case when upper follows lower AND lower follows upper (which isn't handled in your attempt)

line1 ='ewtloYgcFQaJNhHVGxXDiQmzjfcpYbzxlWrVcqsmUbCunkfxZWDZjUZMiGqhRRiUvGmYmvnJIH EmbT'
for i, j in zip(line1[1:],line1):
   if (i.islower() and j.isupper()) or (i.isupper() and j.islower()):
    print(i,j)

(note: no need to convert string to lists, strings can be iterated as-is)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download