Anoop
Anoop

Reputation: 1435

String reverse in 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???

Upvotes: 7

Views: 806

Answers (5)

ekhumoro
ekhumoro

Reputation: 120568

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

Upvotes: 0

seggy
seggy

Reputation: 434

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)

Upvotes: 0

NPE
NPE

Reputation: 500147

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

Upvotes: 3

Sylvain Defresne
Sylvain Defresne

Reputation: 44463

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!

Upvotes: 6

moises_mozart
moises_mozart

Reputation: 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(' ') ]))

Upvotes: -1

Related Questions