-1

So I have to create a function who take a list like this: [d,o,g] --> each caracter has a position and the return is the reverse word... So far I have this:

def invertido(x):
    largo= len(x)
    for i in range (0, largo/2):
        x[i] = x[largo -i]
    print x

I have the following error: TypeError: 'str' object does not support item assignment

PyNEwbie
  • 4,882
  • 4
  • 38
  • 86
stroncod
  • 33
  • 7

1 Answers1

2

You can do this directly using the indexing syntax in Python. Try:

word_inverted = word[-1::-1]

This syntax means "start at the last letter in word (index -1), move backwards one letter at a time (the -1 at the end), and move through all of the letters in the word (the :: in the middle)"

In general, you can index an array (a string is just an array of characters) with the syntax array[first:last:step], where first is the first item that you want, last is the first item that you don't want (i.e. the last item you get is the item right before last) and step is how far you want to move for each successive item.

You can also use some shortcuts to just grab all letters from the beginning of the word to last with array[:last:step], all letters from first to the end with array[first::step], and all letters at some interval step with array[::step]. Lastly, if you enter a negative value for step, then you step backwards through the array.

Engineero
  • 12,340
  • 5
  • 53
  • 75