7

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???

0

5 Answers 5

6

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!
Sign up to request clarification or add additional context in comments.

2 Comments

This doesn't work correctly on string containing hyphens. I think the pattern should be changed to re.compile('([^\w\-])')
(\W+) would be better than (\W) - Note that \W symbolizes other characters than alphanumeric ones and underscore while OP didn't defined a word as possibly containing an underscore
3

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!'

2 Comments

that's a nice way, in my opinion.
Note that \w symbolizes alphanumeric and underscore while OP didn't defined a word as possibly containing an underscore
0

My answer, more verbose though. It handles more than one punctuation mark at the end as well as punctuation marks within the sentence.

import string
import re

valid_punctuation = string.punctuation.replace('-', '')
word_pattern = re.compile(r'([\w|-]+)([' + valid_punctuation + ']*)$')

# reverses word. ignores punctuation at the end.
# assumes a single word (i.e. no spaces)
def word_reverse(w):
    m = re.match(word_pattern, w)
    return ''.join(reversed(m.groups(1)[0])) + m.groups(1)[1]

def sentence_reverse(s):
    return ' '.join([word_reverse(w) for w in re.split(r'\s+', s)])

str1 = raw_input('Enter the sentence: ')
print sentence_reverse(str1)

Comments

0

Simple solution without using re module:

print 'Enter the string:'
string = raw_input()

line = word = ''

for char in string:
    if char.isalnum() or char == '-':
        word = char + word
    else:
        if word:
            line += word
            word = ''
        line += char

print line + word

Comments

-1

you can do this.

print"Enter the string:"

str1=raw_input()

print( ' '.join(str1[::-1].split(' ')[::-1]) )

or then, this

print(' '.join([w[::-1] for w in a.split(' ') ]))

1 Comment

the output would be exactly like what OP already has: "naC uoy pleh !em".

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.