Day 64: Check If A String is a Palindrome With Python

 

We get a string and check if it is a palindrome:

 

# Find out if a word is a palindrome
def palin(word):
    ''' take word, build inverted string
    and check if it is a palindrome '''

    word = word.replace(".", "")    # get rid of eventual "."
    word = word.lower()             # make lowercase

    length = len(word)
    new = list("")                  # build an empty list for the inversed string
    index = -1                      # -1 so we start building in reverse order

    # take every letter and add it to new list in reverse order
    for i in word:
        new.insert(index, i)
        index -= 1

    # change list to string
    new_str = "".join(new)

    # get rid of any spaces in a sentence
    word_stripped = word.replace(" ", "")
    new_stripped = new_str.replace(" ", "")

    # check if word and the reverse string are the same
    if (word_stripped == new_stripped):
        return (word + ": This is a palindrome")
    else:
        return (word + ": This is NOT a palindrome")

print(palin("Anna"))                    # anna: This is a palindrome

print(palin("peter"))                   # peter: This is NOT a palindrome

print(palin("Name not one man."))       # name not one man: This is a palindrome

Schreibe einen Kommentar

Deine E-Mail-Adresse wird nicht veröffentlicht. Erforderliche Felder sind mit * markiert.

Diese Website verwendet Akismet, um Spam zu reduzieren. Erfahre mehr darüber, wie deine Kommentardaten verarbeitet werden.