简体   繁体   中英

How to remove palindromic words from a string

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?

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]

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

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 as 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)
txt = "malayalam is my mother tongue"
splittedArray = txt.split()
for s in splittedArray:
    if( s == s[::-1]):
        splittedArray.remove(s)
print(' '.join(splittedArray))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM