FAQ: Code Challenge: String Methods - Reverse

range(start, stop, step)

The inputs are all integers (required). Only the stop value is needed if the start is 0 and the step is 1. The stop value is excluded from finished range object.

range(10)  =>  range(0, 10)

which when iterated (or cast to a list) will result in the sequence,

0, 1, 2, 3, 4, 5, 6, 7, 8, 9

To generate the opposite sequence,

range(10 - 1, -1, -1)

9, 8, 7, 6, 5, 4, 3, 2, 1, 0

The stop of -1 is excluded, so we end on zero.

5 Likes

Thank you very much sir! It’s crystal clear :slight_smile:

1 Like

Found another simiar one without the range:

def reverse_string(word):
  output_string = ""
  a = -1
  for i in word:
    output_string += word[a]
    a = a - 1
  return output_string

Hello, I’m a new learner and really have a problem with code. Concerning string methods - reverse this is my try:

def reverse_string(word):
new_word = “”
for i in range(len(word)-1, 0, -1):
new_word += word[i]
return new_word

print(reverse_string(“Codecademy”)) —> ymedacedo
how to solve it , cause it should print “ymedacedoC”

Thx in advance

Thx @mtf I just posted a question concerning range(start, stop step), and your explanation is really helpful

To generate the opposite sequence,

range(10 - 1, -1, -1)

9, 8, 7, 6, 5, 4, 3, 2, 1, 0
:+1:

1 Like

I don’t understand how this gives the word in reverse, can someone explain?

Welcome to the forums!

I’ll explain this with one change: reversed_str = "" rather than reversed_str = " ", since the space could cause the reversed string not to be an exact match.

We initially assign reversed_str the value of an empty string. Then, we have a for loop that iterates over every character in word. Every iteration, we assign reversed_str the value of letter concatenated to reversed_str. This means that we are adding each subsequent character in word before the existing reversed_str. Once we’ve iterated through every character in word, we return the reversed string.

Example

reverse_string("hello")

Iteration 1: We assign reversed_str to the value of "h", the first character in word, concatenated to reversed_str, which is currently an empty string. Now reversed_str == "h".
Iteration 2: We assign reversed_str to the value of "e", the second character in word, concatenated to the current value of reversed_str, which is "h". Now reversed_str == "eh".
Iteration 3: We assign reversed_str to the value of "l", the third character in word, concatenated to the current value of reversed_str, which is "eh". Now reversed_str == "leh".
And so on… until we have iterated through every character in word. Now reversed_str == "olleh" and we return it.

1 Like

My solution:

def reverse_string(word):
  new_word = ''
  for i in range(len(word)):
    if i < len(word):
      new_word += word[-abs(i)-1]
    else:
      new_word += word[0]
  return new_word

My solution is.

def reverse_string(word):
  rever = ""
  for i in range(1, len(word) + 1):
    rever += word[-i]
  return rever
1 Like

Solution :heart_eyes:
def reverse_string(word):

result=’’

for index in range(1,len(word)+1):

result+=word[len(word)-index]

return result

Refrain from posting solutions on the forums. We want to encourage learners to learn and solve the exercises themselves rather than copying someone else’s code.

I used the following code for my solution but got an error:

def reverse_string(word): reverse = "" i = len(word) - 1 for i >= 0: reverse += word[i] i -= 1 return reverse

My logic is this:

  1. start off with empty “reverse” string.
  2. set i to last index (i realize it can be set to -1, but well).
  3. iterate i from last index to 0 by saying i must be greater than or equal to 0 (and stop the loop when i gets less then 0)
    This shows a syntax error in the " for" line. I don’t understand what is the syntax error here? Can anyone please explain?

The syntax error is the inequality. We can only iterate with in.

for j in range(len(word)):

That is a signature for iterating a range (0…N).

for x in obj:

Is a signature for iterating the values of a list, or the keys of a dictionary.

Thank you for clarifying! I just went and checked, and confused the syntax for iterating with “while” with “for” loops.
I am assuming that the relational operators can be used with “while”?

Yes, because while is conditional. for is iterative. The latter iterates over a sequence; the former continues until the condition is no longer met.

1 Like

This explained a lot lol.

still kind of proud of this but I need to understand range better heh:

def reverse(string1):

        emptylist = []

        for index in range(len(string1)):

          emptylist.append(string1[index - index - index -1])

        return "".join(emptylist)
1 Like

The first two operands cancel out so what we are left with is,

-index - 1
1 Like

i was proud of my solution until i saw yours and realized i did the same thing but more complicated.

def reverse_string(word):
  gnirts = ""
  for i in range(1, len(word) + 1):
    gnirts = gnirts + word[i * -1]
  return gnirts

the only thing im proud of now is that i used the reverse of ‘string’ for my output variable :sweat_smile:

A post was split to a new topic: Explain how the code works?

Hi guys, have to make the topic back as I really need your help. I went through all the notes here but am still nowhere close to understanding the given solution (not telling about finding it out myself).

So basically my question is the following line:
for i in range(len(word)-1, -1, -1):

If for .range() we have (start, end, step) then I understand why it starts with -1 in this case. But the rest is totally complicated for me.

Another point is that I don’t even understand the position of those elements. Why do all -1 go afterward?
For a regular position in another we would use, wouldn’t we?
for i in range(0, len(word), 2):

This is so far the most dragging thing but I’m determined to get it. Please, advise (I’m no coder so I’d appreciate plain English.