LulzSec
LulzSec

Reputation: 39

reversing each word in sentence using python

I'm new in python. I'm trying to reverse each word in the sentence. I wrote following code for that and it is working perfeclty.

My code: [From answer]

import re
str = "I am Mike!"

def reverse_word(matchobj):
    return matchobj.group(1)[::-1]

res = re.sub(r"([A-Za-z]+)", reverse_word, str)
print(res)

But I want to add one condition in that..only words should reverse not any symbol.[ except alphanumerical words and words contains hyphen]

Updated##

Sample: input: "I am Mike! and123 my-age is 12"

current output: "I ma ekiM! dna123 ym-ega si 12"

required output: "I ma ekiM! 321dna ege-ym si 21"

Upvotes: 2

Views: 155

Answers (3)

Kunal Mukherjee
Kunal Mukherjee

Reputation: 5853

The Regex: ([A-Za-z]+)

You can use the character class [A-Za-z] for checking any word with one or more length, capture it then reverse the group 1 using a function using the re.sub function.

import re
str = "I am Mike!"

def reverse_word(matchobj):
    return matchobj.group(1)[::-1]

res = re.sub(r"([A-Za-z]+)", reverse_word, str)
print(res)

Outputting:

'I ma ekiM!'

Update:

You can tweak the code a little to acheive your results:

import re
str = "I am Mike! and123 my-age is 12"

def reverse_word(matchobj):
     hyphen_word_pattern = r"([A-Za-z]+)\-([A-Za-z]+)"
     match = re.search(hyphen_word_pattern, matchobj.group(1))
     if match:
         return re.sub(hyphen_word_pattern, f"{match.group(2)[::-1]}-{match.group(1)[::-1]}", match.group(0))
     else:
         return matchobj.group(1)[::-1]

res = re.sub(r"([A-Za-z]+\-?[A-Za-z]+)", reverse_word, str)
print(res)

Outputting:

I ma ekiM! dna123 ega-ym si 12

Upvotes: 2

Tom Lubenow
Tom Lubenow

Reputation: 1161

Don't use re at all

def reverse_words_in_string(string):
    spl = string.split()
    for i, word in enumerate(spl):
        spl[i] = word[::-1]
    return ' '.join(spl)

gives 'I ma !ekiM 321dna ega-ym si 21'

Upvotes: 2

Tim Biegeleisen
Tim Biegeleisen

Reputation: 522817

One approach which might work would be to make an additional iteration over the list of words and use re.sub to move an optional leading punctuation character back to the end of the now reversed word:

s = "I am Mike!"
split_s = s.split()
r_word = [word[::-1] for word in split_s]
r_word = [re.sub(r'^([^\s\w])(.*)$', '\\2\\1', i) for i in r_word]
new_s = " ".join(r_word)
print(new_s)

I ma ekiM!

Upvotes: 0

Related Questions