0

This is the code I have written:

import sys
import string

def reverse(li):
    li=li[::-1]
    return li

a=raw_input("Enter first line ")
c=[]
c=a[0:2]
a=reverse(a)
b=[]
i=0
for i in range(0, len(a)):
    if(a[i]==' '):
        b=a[:i]
        b=reverse(b)
b.append(c) 
print b

Here the error is: 'str' object has no attribute 'append' on line b.append(c).

Why is this error creeping up? Where am I going wrong?

3 Answers 3

1

It's because you make b a string with this line:

b=str(reverse(b))

Doing so overshadows the list. Pick a different variable name to solve your problem.

Also, there is no need to make a function reverse because Python has a built-in reversed function:

>>> a = [1, 2, 3]
>>> reversed(a)
<listreverseiterator object at 0x015AC6B0>
>>> list(reversed(a))
[3, 2, 1]
>>>
Sign up to request clarification or add additional context in comments.

1 Comment

@Downvoter - Why did I get a downvote for this? My answer is right and also solved the OP's problem. What is wrong?
1

You are turning b into a string in the line above it:

b=str(reverse(b))

Hence, b is now a string and it won't support the .append() method which is for lists.

Comments

0

In python str object does not have an append() method but list object has append() method

In your code b = [] Initially you defined b as a list

b=reverse(b) But this statement in your code will convert b from list to str

As str object i.e b does not have an append() you will get an error

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.