Reverse


#1



7.Reverse

i mean i have a doubt like why dont this initialization of strings work


python
Replace this line with your code.
def reverse(text):
x=len(text)-1
te=""
i=0
while(x>=0):
te[i]=str(text[x])
x-=1
i+=1
return te


#2

Hi, @coreninja83990 ,

An object of str type is immutable, so you cannot change a character in a str like this ...

te[i]=str(text[x])

Instead, you can start with an empty list, and assemble the characters in reverse order in that list. Then use the join method to combine the reversed characters back into a str object.


#3

ya i tried even with it but it didnt workup


#4

Actually i just want to know the reason why doesint the above initialization in 6 line of code doesint work even if str is removed


#5

Hi, @coreninja83990 ,

There are several changes that need to be made for your code to work.

It would be best if your posted code were formatted, so that we could see its indentation. See How do I format code in my posts?.

Initialize te as an empty list, rather than as a str ...

te = []

Along with that change, instead of this ...

te[i]=str(text[x])

... you would append characters to te ...

te.append(text[x])

After the loop, join the characters back together into a str ...

return "".join(te)

#6

well sir i here have'nt come up for solution as i already said above cant we initialize 2 strings like in c (b[j]=a[i]) in such manner


#7

In Python, if b represents a str, you cannot do this ...

b[j]=a[i]

A Python str cannot be modified.


#9

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.