- Trending Categories
- Data Structure
- Operating System
- C Programming
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Python program to sort Palindrome Words in a Sentence
When it is required to sort the palindrome words present in a sentence, a method is defined that takes a string as a parameter and first ensures that it is a palindrome. Then it sorts all the words of a string and returns it as output.
Below is a demonstration of the same
def check_palindrome(my_string): if(my_string == my_string[::-1]): return True else: return False def print_sort_palindromes(my_sentence): my_list =  my_result = list(my_sentence.split()) for i in my_result: if(check_palindrome(i)): my_list.append(i) my_list.sort() j = 0 for i in range(len(my_result)): if(check_palindrome(my_result[i])): my_result[i] = my_list[j] j = j + 1 for i in my_result: print(i) my_sentence = "hi madam, how are u" print("The sentence is ") print(my_sentence) print("The result is :") print_sort_palindromes(my_sentence)
The sentence is hi madam, how are u The result is : hi madam, how are u
A method named ‘check_palindrome’ is defined that takes a string as a parameter.
It checks to see if a string is a palindrome.
Another method named ‘print_sort_palindromes’ is defined that takes a sentence as a parameter.
Inside this function, an empty list is created.
The sentence is split based on spaces, and converted into a list of elements.
The list elements are iterated over, and are checked to see the words in the sentence are palindromes.
If yes, it is appended to the empty list.
This list is sorted.
Outside the method, the sentence is defined and is displayed on the console.
The method is called by passing the parameter.
The output is displayed on the console.
- Count palindrome words in a sentence in C++
- Python program to count words in a sentence
- Python program to sort out words of the sentence in ascending order
- Java program to sort words of sentence in ascending order
- Count words in a sentence in Python program
- Print longest palindrome word in a sentence in C Program
- Rearrange Words in a Sentence in C++
- C# program to remove all duplicates words from a given sentence
- Java program to remove all duplicates words from a given sentence
- Python - Generate all possible permutations of words in a Sentence
- Program to reverse a sentence words stored as character array in C++
- Java program to swap first and last characters of words in a sentence
- Python - Check if given words appear together in a list of sentence
- Python – Sort Matrix by Palindrome count