Python line reverse

Write a simple program that reads a line from the keyboard and prints the same line where each word is reversed. A word is defined as a continuous sequence of alphanumeric characters or hyphens ('-). For example, if the input is "you can help me!" the output should be "naC uoy pleh em!"

I just tried with the following code, but there are some problems with it,

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

He prints "naC uoy pleh! Em", just look at the exclamation (!), This is the problem here. Can anyone help me ???

+7
source share
5 answers

You can use re.sub() to find each word and cancel 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!' 
+3
source

The easiest way is 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)) 

At startup, you get:

 Enter the string: Can you help me! naC uoy pleh em! 
+6
source

My answer is more detailed. It processes more than one punctuation mark at the end, as well as punctuation marks in a 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 (ie 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) 
0
source

A simple solution without using the 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 
0
source

can you 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(' ') ])) 
-one
source

All Articles