Saturday 3 December 2011

String reverse in Python

During this post I want share an interesting string reverse solution in python. Here is the question.
Write a simple program that reads a line from the keyboard and outputs the same line where every word is reversed. A word is defined as a continuous sequence of alphanumeric characters or hyphen (‘-’). For instance, if the input is
“We are at Ignite Solutions!”
the output should be
“eW era ta etingI snoituloS!”

At first, I just tried with the following simple code,
    print"Enter the string:"
    str1=raw_input()
    print (' '.join((str1[::-1]).split(' ')[::-1])) 
It prints the outputs like, eW era ta etingI !snoituloS. Is it correct??
At first look we thought its a correct answer, but actually it is  wrong. Can you got the problem?
The real problem is in the position of exclamation(!).

I have found one new solution for this problem, please listen here.
    str1=raw_input("Enter the string: ")
    #re.sub() used to find each word and reverse it
    print re.sub(r'[-\w]+', lambda w:w.group()[::-1],str1)
It prints the output like this, eW era ta etingI snoituloS!

No comments:

Post a Comment