Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String reverse in Python

Tags:

python

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 “Can you help me!” the output should be “naC uoy pleh em!”

I just tryed with the following code, but there are some problem with it,

print"Enter the string:"
str1=raw_input()
print (' '.join((str1[::-1]).split(' ')[::-2]))

It prints "naC uoy pleh !em", just look the exclamation(!), it is the problem here. Anybody can help me???

like image 328
Anoop Avatar asked Dec 02 '11 15:12

Anoop


2 Answers

The easiest is probably to use the re module to split the string:

import re
pattern = re.compile('(\W)')
string = raw_input('Enter the string: ')
print ''.join(x[::-1] for x in pattern.split(string))

When run, you get:

Enter the string: Can you help me!
naC uoy pleh em!
like image 54
Sylvain Defresne Avatar answered Sep 21 '22 14:09

Sylvain Defresne


You could use re.sub() to find each word and reverse it:

In [8]: import re

In [9]: s = "Can you help me!"

In [10]: re.sub(r'[-\w]+', lambda w:w.group()[::-1], s)
Out[10]: 'naC uoy pleh em!'
like image 30
NPE Avatar answered Sep 22 '22 14:09

NPE