[Tutor] detecing palindromic strings

Eric Brunson brunson at brunson.com
Sat Sep 29 02:31:13 CEST 2007


Christopher Spears wrote:
> I'm trying to write a script that detects if a string
> is palindromic (same backward as it is forward).  This
> is what I have so far:
>
> #!/usr/bin/env python
>
> my_str = raw_input("Enter a string: ")
>     
> string_list = []
>
> for s in my_str:
>     string_list.append(s)
>
> string_list_orig = string_list
>
> string_list.reverse()
>
> print string_list_orig
> print string_list
>
> The problem is that the script gives results like so:
> io at io-station-1 ./chap6 117> python palindromic.py
> Enter a string: abc
> ['c', 'b', 'a']
>   

Well, since you've converted the string to a list, what you would like 
to do is:

print "".join( string_list_orig )

to connect them back together.

However, you can simplify the code greatly:

 >>> s = "abcd"
 >>> print s[::-1]
dcba
 >>> if s == s[::-1]:
...     print "yay"
...
 >>> s = "abcdcba"
 >>> if s == s[::-1]:
...     print "yay"
...
yay


> ['c', 'b', 'a']
>
> Now I understand pointers and Python!  :-)  Since
> string_list_orig is pointing to string_list, when I
> reversed string_list, string_list_orig was reversed as
> well.
>
> How do I get around this?  Is there a better way to
> write this script?  I can't figure out how to loop
> through a string starting from the last character.
>
>
> "I'm the last person to pretend that I'm a radio.  I'd rather go out and be a color television set."
> -David Bowie
>
> "Who dares wins"
> -British military motto
>
> "I generally know what I'm doing."
> -Buster Keaton
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>   



More information about the Tutor mailing list