[It learning] How Python handles exception special characters

Source: Internet
Author: User

A byte of Python in the "Input and Output" section has a small example (io_input.py) dealing with palindrome. The author left a study questions.

How to remove punctuation, ignore the case, and then consider whether palindrome?

You can learn the RE module and learn how to deal with Str.

Method 1: Use the RE regular expression to treat special characters as empty strings.

ImportRedefreverse (text):returnText[::-1]defis_palindrome (text):returnText = =reverse (text) something= Input ("Enter Text:") Something= Re.sub (r'[,. -!?:]',"', something) something=Something.lower ()Print(something)ifIs_palindrome (something):Print("Yes, it is a palindrome")Else:    Print("No, it is not a palindrome")

Method 2: Use a loop to determine whether each character is inside a special string, and then replace the special character with a space.

Finally, use join and split to replace the space.

defreverse (text):returnText[::-1]defis_palindrome (text):returnText = =reverse (text) something= Input ("Enter Text:") Specialstr= (",",".","-","!","?",":") Prostr=list (something) forIinchRange (len (something)):ifSomething[i]inchSpecialstr:prostr[i]=" "
#将列表变为字符串something="". Join (PROSTR)

#将字符串以空格为分隔符, becomes a list, and then becomes a string that does not contain spaces
something="". Join (Something.split (" "))
#变为小写字符串
= Something.lower ()
#打印字符串, verify that the conversion is good
Print (something) if Is_palindrome (something): Print ("Yes, it is a palindrome") Else : Print ("No, it is not a palindrome")

Re Module reference Documentation:

Http://www.cnblogs.com/sevenyuan/archive/2010/12/06/1898075.html

[It learning] How Python handles exception special characters

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.