find all possible palindromes in a string in Python

 find all possible palindromes in a string in Python




To find all possible palindromes in a string in Python, you can use a brute-force approach that checks all possible substrings of the string to see if they are palindromes. Here is an example of how you might do this:

def find_palindromes(string):

    palindromes = []

    for i in range(len(string)):

        for j in range(i, len(string)):

            substr = string[i:j+1]

            if substr == substr[::-1]:

                palindromes.append(substr)

    return palindromes


string = "BCdedCB"

palindromes = find_palindromes(string)

print(palindromes) # Outputs ["BCdedCB", "CdedC", "ded"]


In this example, the find_palindromes function takes a string as input and returns a list of all palindromes found in the string. It uses two nested for loops to iterate through all possible substrings of the string, and then checks if the substring is a palindrome using string slicing. If the substring is a palindrome, it is added to the list of palindromes.

Post a Comment

0 Comments