Categories
Uncategorized

Reverse a String – Python

As sad as it may sound, this is how I relax.

EDIT:
After reading this Reddit post, it seems the correct answer is

str_my_string = 'hello'

print str_my_string[::-1]

Inspired by this reddit post, I’ve decided to have a go at some of them.

So today I will have a go at reversing a string.

The Challenge

Enter a string and the program will reverse it and print it out.

The logic behind the solution

You count the number of letters in the string, and then you append each letter to a list in reverse order.

Then you join the list and print the whole thing out….easy.

The Code

Here it is

# _reverseString.py
# write string you want reversed
str_the_string = raw_input('Enter string: ')

# the output list of all letters
list_output = []

# loop through letters and append to above list
for i in range(1,len(str_the_string)+1):
    # this is the bit that reverses the order
    int_pos = len(str_the_string) - i
    # and this bit appends to the list
    list_output.append(str_the_string[int_pos])

# join list and print
print ''.join(list_output)

So if we run it, we get this in the terminal (this is an example)

$python _reverseString.py
Enter string: Something Really Interesting
gnitseretnI yllaeR gnihtemoS

And now, for shts and giggles…in C

#include <stdio.h>
#include <string.h>


int main(){

	// set variables
	char str_main[50], str_rev[50];
	int str_len, x, y;

	// Ask to enter string
	printf("Enter string to reverse:\n\t");

	// Enter string
	scanf("%[^.*$\n]",str_main);

	// find the legth of the string
	str_len = strlen(str_main)-1;

	// loop the thing backwards
	y = 0;
	for (x=str_len;x>=0;x--){
		str_rev[y] = str_main[x];
		y++;
	};

	// Print output
	printf("The reverse is:\n");
	printf("\t%s\n",str_rev);

	return 0;
}

One reply on “Reverse a String – Python”

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s