Thursday, 19 May 2016

String Reverser

STRING-REVERSER

This will be my first post!

OBJECTIVE: Print out an inputted string in reverse.

So here's my train of thought.. I first want to prompt an input from the user. Let's do that:

word = raw_input('Enter a string to be reversed: ');

The variable "word" will take in the value of input from function raw_input, and the computer will print "Enter a string to be reversed".

The second step is to think about how to reverse something that's given:

 - We know that a string contains indexes for each character. A string "hello" will have h assigned to index 0, e assigned to index 1 and so on.

 - And we also know the function len(string) which will output the length of the given string.

What's the link between the two?
Well the last index of the string is equal to the length of the string minus one. So:

print (word[len(string)-1]);

Would print the last character of the string.
Putting this into thought, we would essentially want to repeat this all the way until the beginning of the string, or when len(string)-1 == -1. We do this using FOR loops!

The syntax for FOR loops is:

for i in xrange(starting value, end value, increment)

As previously stated, we'd want to start off with the last character of the string, which would be word[len(string)-1], so the numerical value would be len(string)-1.
The end value would be when it reaches the first character of the string. The index of the first character is 0, so 0-1 would be -1.
Finally, the increment should be -1 because we'd want to go down the index of the string, 1 character at a time.

To put this all together, we'd want to use the join function to combine these strings, as such:

print ''.join([word[i] for i in xrange(len(word)-1, -1, -1)]);

The '' is there as a blank space to add the corresponding individual strings to, hence followed by join.

TL;DR:

word = raw_input('Enter a string to be reversed: ');
print ''.join([word[i] for i in xrange(len(word)-1, -1, -1)]);


Example of String Reverser using Notepad++

No comments:

Post a Comment