def reverse(word):
x = ''
for i in range(len(word)):
x += word[len(word)-1-i]
return x
- i do not understand the x += word(len(word)-1-i
- i am new to python and trying to understand the thinking behind this line of code. if someone could explain it to me, it would be very helpful. Thank you.
len(word) is the number of letters in word
len(word)-1 is the index of the last letter in word. Python indexing starts with 0.
word[len(word)-1] is the last letter in word.
x = '' sets x to an empty string
x += 'a' is the same as x = x + 'a'
Adding two strings makes a new string that is the two strings concatenated. if x == 'b', x += 'a' is the same as x = 'b' + 'a' or x = 'ba'
x += word[len(word)-1] gets the last letter in word and adds it to the end of whatever is in 'x'.
This program loops through the letters in word starting at the end. Ig adds the letters to x. In the end, x has the same letters as word, but in reverse order.
(Apr-21-2020, 03:05 AM)deanhystad Wrote: [ -> ]len(word) is the number of letters in word
len(word)-1 is the index of the last letter in word. Python indexing starts with 0.
word[len(word)-1] is the last letter in word.
x = '' sets x to an empty string
x += 'a' is the same as x = x + 'a'
Adding two strings makes a new string that is the two strings concatenated. if x == 'b', x += 'a' is the same as x = 'b' + 'a' or x = 'ba'
x += word[len(word)-1] gets the last letter in word and adds it to the end of whatever is in 'x'.
This program loops through the letters in word starting at the end. Ig adds the letters to x. In the end, x has the same letters as word, but in reverse order.
thank you for your response. but i see it has -1 and -i. i dont know what that really means. thanks again
Use pen and paper. Write down a string and label each character with its index. Then, calculate the value of len(word) - 1 - i
and see which character in the string that refers to. Repeat it for each iteration of the loop.
Another 'cheap' way is to let Python do the lifting:
>>> word = 'hello'
>>> x = ''
>>> for i in range(len(word)):
... indice = len(word) - 1 - i
... letter = word[indice]
... x += letter
... print(f'{i}/{len(word)}: indice is {indice}, letter is {letter} and x is {x}')
...
0/5: indice is 4, letter is o and x is o
1/5: indice is 3, letter is l and x is ol
2/5: indice is 2, letter is l and x is oll
3/5: indice is 1, letter is e and x is olle
4/5: indice is 0, letter is h and x is olleh
There are several other ways to achieve desired result:
>>> ''.join(word[-i] for i, _ in enumerate(word, start=1))
'olleh'
>>> ''.join(reversed(word))
'olleh'
From:
https://stackoverflow.com/questions/4841...-in-python
+= adds another value with the variable's value and assigns the new value to the variable.
>>> x = 3
>>> x += 2
>>> print x
5
-=, *=, /= does similar for subtraction, multiplication and division.
You could think of as a shortcode to use some operators but depends on what you trying to achieve.
>>> a='hello'
>>> print(a[::-1])
olleh