简体   繁体   中英

I need help finishing my palindrome checking python code

i'm kind of a noob in python. This is a project I need to submit by midnight. the more I edit, the worse off it seems to get.

so here's my code:

import string

def palendrone():

    input = raw_input('give us some stuff and we will see if it is a palendrone:')
    lowercase = string.lower(input)

    new_string = ''
    markList = [".", " ", ";", ":", "!", "?", "/", "," , "#", "@", "$", "&", ")", "(", "\", '*', '^'"]

    for item in markList in lowercase:    
        del(item) in lowercase

    for letter in (lowercase):
        new_string += letter

    backwards_string = new_string[::-1]

    print new_string
    print backwards_string

    return backwards_string == new_string

I mostly need help trying to get rid of the punctuation. That has proven the most difficult for me.

What would be the best way to do that in this kind of situation?

You are almost there. The logic you want is "for each item in markList, if that item exists in lowercase, delete it".

You made a good attempt at translating that into code, but unfortunately there is no such statement as del(item) in lowercase , to delete things from strings, you need to replace them with something else.

Here is how you translate that:

for item in markList:
   if item in lowercase:
      lowercase = lowercase.replace(item, '')

You don't need the second loop at all, instead:

backward_string = lowercase[::-1]

I mostly need help trying to get rid of the punctuation.

One of the ways to get rid of the punctuation is

import re
new_string = re.sub('[:?!/]', '', input)

Couple of things here :

1) You have to escape \\ which is done like "\\\\" .

2) Iterating over the input string and rejecting if something comes in markList is algorithmically better

import string

def palindrome():

    input = raw_input('give us some stuff and we will see if it is a palendrone:')
    lowercase = string.lower(input)

    new_string = ''
    markList = [".", " ", ";", ":", "!", "?", "/", "," , "#", "@", "$", "&", ")", "(", "\\", '*', '^']


    for letter in lowercase:
        if letter not in markList:
            new_string+=letter

    backwards_string = new_string[::-1]

    print new_string
    print backwards_string

    return backwards_string == new_string

Note: There are many ways to construct the cleaned string. For one such way refer to Antony's answer.

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