Home > OS >  How to remove palindromic words from a string
How to remove palindromic words from a string

Time:11-02

Here I have been trying to remove the palindromic words from the given string. This is my code:

lis = list(text.split(" "))
newlis=[]
for i in range(len(lis)):
   if (lis[i] != lis[i][::-1]):
       newlis.append(lis[i])
print(newlis)

If the input is

Nair speaks malayalam

I get the output as

['Nair', 'speaks', 'Malayalam']

Why the palindromic words aren't removed?

CodePudding user response:

You can check if a string is palindrome with str(n) == str(n)[::-1]

So you can create a function and filter the list with it as follows:

def is_palindrome(n):
  return str(n) == str(n)[::-1]

lis = [wrd for wrd in list(text.split(" ")) if not is_palindrome(wrd)]

Here's a working repl.it project:

https://replit.com/@HarunYlmaz/Palindrome#main.py

UPDATE

As @Passerby stated in the comment, you may need to ignore case. If so, you can use lower() method as well:

str(n).lower() == str(n).lower()[::-1]

CodePudding user response:

List comprehension or filter:

>>> [i for i in text.split() if i != i[::-1]]
['Nair', 'speaks']

>>> list(filter(lambda x: x != x[::-1], text.split()))
['Nair', 'speaks']
>>> 

Or to ignore case:

>>> [i for i in text.split() if i.lower() != i[::-1].lower()]
['Nair', 'speaks']

>>> list(filter(lambda x: x.lower() != x[::-1].lower(), text.split()))
['Nair', 'speaks']
>>> 

CodePudding user response:

Your code is fine. May be, in the question you've typed "malayalam" but actually it is "Malayalam". Lower case "m" is not equal to upper case "M" so it doesn't remove it. If you don't want case sensitive, then use .lower() method. This will make all the letters small and then check for palindrome which makes it non case sensitive. If you want input from the user ad well to make it dynamic, here's another method. Seperate the words using split() function. Check for every word whether it is palindrome. If yes, remove it from the list, else continue. After than, unpack your list. Your code:

x=input("Enter string")
y=list(x.split())
for i in y:
    if i.lower()==i[::-1].lower():
        y.remove(i)

print(*y)
  • Related