1.[文件]
MyStrClass.py ~ 2KB
下载(6)
class EasyStrClass:
def __init__(self, string):
self.__string = string
def containSubStr(self, skey):
if skey in self.__string:
return self.__string + " contains " + skey
else:
return self.__string + " does not contain " + skey
def isPalindrome(self):
""" Those parts are original codes, they don't require extra
spaces, but is not concise enough.
low = 0
high = len(self.__string) - 1
while low < high:
if self.__string[low] != self.__string[high]:
return self.__string + " is not a palindrome"
low += 1
high -= 1
return self.__string + " is a palindrome"""
"""A more concise implementation, thanks to 黑暗圣堂武士:"""
temp = self.__string[::-1]
if temp == self.__string:
return self.__string + " is a palindrome"
return self.__string + " is not a palindrome"
#Return decimal number for a single char:
def hexCharToDecimal(self, ch):
if 'A' <= ch <= 'F':
return 10 + ord(ch) - ord('A')
else:
return ord(ch) - ord('0')
#Return the str into decimal if it is a hexidecimal number:
def hexToDecimal(self):
decimalVal = 0
hexStr = self.__string.upper()
for index in range(len(hexStr)):
ch = hexStr[index]
if 'A' <= ch <= 'F' or '0' <= ch <= '9':
decimalVal = decimalVal * 16 + self.hexCharToDecimal(ch)
else:
return None
return decimalVal
"""
If you are trying to run this code
in other python files
add this line:
from MyStrClass import EasyStrClass"""
string = input("Enter a string: ").strip()
strkey = input("Enter the string you want to check: ")
strclass = EasyStrClass(string)
print(strclass.isPalindrome())
print(strclass.containSubStr(strkey))
print(strclass.hexToDecimal())