
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
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.
Example
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)
Output
The sentence is hi madam, how are u The result is : hi madam, how are u
Explanation
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.
- Related Articles
- Python program to sort out words of the sentence in ascending order
- Count palindrome words in a sentence in C++
- Python program to count words in a sentence
- 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
- Program to reverse a sentence words stored as character array in C++
- Python - Generate all possible permutations of words in a Sentence
- C# program to remove all duplicates words from a given sentence
- Java program to remove all duplicates words from a given sentence
- Java program to swap first and last characters of words in a sentence
- Rearrange Words in a Sentence in C++
- Python – Sort Matrix by Palindrome count
- Python - Check if given words appear together in a list of sentence
- Python program to reverse each word in a sentence?
