Diwaker Singh
Diwaker Singh

Reputation: 31

How to reverse individual words in a string without reversing the whole string?

i am new to Python. i want reverse a string's words without reversing the whole string. And words which are repeating should not get reversed.

i want something like this-

Input- Dom is an artist, Dom lives in UK. Output- Dom si na tsitra, Dom sevil ni KU.

Upvotes: 0

Views: 1323

Answers (2)

Steven Summers
Steven Summers

Reputation: 5384

You can use str.split which will create a list containing each word and collections.Counter to easily count each word in that list.

from string import punctuation # '!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~'
from collections import Counter

def reverse_text(text):
    punc = ''

    # remove any punctuation from end of text
    while text[-1] in punctuation:
        punc = text[-1] + punc
        text = text[:-1]

    # reverse text and add punctuation back on
    return text[::-1] + punc

inp = "Dom is an artist, Dom lives in UK"
words = inp.split() # split input
counter = Counter(words) # count each word. Note: counts exact matches.
# rejoin the string reversing any unique words
res = ' '.join( reverse_text(word) if counter[word] == 1 else word for word in words )
print(res)

# Output
Dom si na tsitra, Dom sevil ni KU

Upvotes: 2

Sohrab Rahimi
Sohrab Rahimi

Reputation: 215

You just need the Counter package to count the number of each unique word in your sentence. You will then loop through your string and see if the word's count equals 1, in that case you reverse the word, other wise you just leave it the way it is. you will then append each resulting item to an emptey list and join them with space (i.e. ' '.join)

from collections import Counter
your_string = "Dom is an artist, Dom lives in UK" 
lst = []
counts = Counter(your_string.split())
for i in your_string.split(): 
   if counts[i]==1:lst.append(i[::-1])
   else: lst.append(i)      
' '.join(i for i in lst)

Upvotes: 1

Related Questions