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???
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!
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!'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With