马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
本帖最后由 qiuyouzhi 于 2020-4-10 12:06 编辑
Python 重构字符串的内置方法
最近闲得没事,突然想起重构字符串的方法了。。
差不多做出了十多个吧,还会继续更新
有一些是我真的没有好思路的,便借鉴了鱼油和网上的思路。
也有一些是功能不完备的(strip),这里放上源代码(顺便做个备份):
class MyStr(str):
def __init__(self,str1):
self.str1 = str1
def Isdigit(self):
for each in self.str1:
try:
int(each)
except:
return False
return True
def Isalpha(self):
temp = "qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM"
for each in self.str1:
if each not in temp:return False
return True
def isspace(self):
for each in self.str1:
if self.str1 != ' ':
return False
return True
def Isalnum(self):
temp = "qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM"
temp2 = "1234567890"
for each in self.str1:
if not (each not in temp or each not in temp2):
return False
return True
def Islower(self):
for each in self.str1:
if ord(each) < 97 or ord(each) > 122:
return False
return True
def Istitle(self):
if ord(self.str1[0]) < 65 or ord(self.str1[0]) > 90:
return False
else:
for each in self.str1[1:]:
if ord(each) < 97 or ord(each) > 122:
return False
else:
return True
def DAS(self):
temp = list(self.str1)
for i in range(len(temp)):
try:
temp.remove(' ')
except ValueError:
break
return ''.join(temp)
# 这里借鉴了网上的思路: https://blog.csdn.net/smfswxj/article/details/79513713
# 原理就是找出字符所在的位置,然后把那个范围里面的字符串(切片)打印出来
def Strip(self, targ = None):
c = 0
nspace = []
for each in self.str1:
c += 1
if each != ' ':
nspace.append(c)
if nspace:
return self.str1[nspace[0]-1: nspace[-1]]
return ''
def Count(self, value):
c = 0
for each in self.str1:
if each == value:
c += 1
return c
def Capitalize(self):
return chr(ord(self.str1[0]) - 32) + self.str1[1:]
def Split(self, svalue):
res = []
length = len(self.str1)
lchar = len(svalue)
for i in range(length):
index = self.str1.find(svalue)
if index == -1:
res.append(self.str1)
return res
else:
res.append(self.str1[:index])
self.str1 = self.str1[index+lchar:]
def Title(self):
def Value(str1):
temp = str1.split(' ')
for i in range(len(temp)):
temp[i] = chr(ord(temp[i][0]) - 32) + temp[i][1:]
yield temp[i]
return ' '.join(Value(self.str1))
# 这里附上普通做法,比较直观
"""res = ''
for each in Value(self.str1):
res += Print(each, end = ' ')
return res[:-1]"""
# 这里附上最简洁的代码
def STitle(self):
return ' '.join((chr(ord(temp[0])-32)+temp[1:] for temp in self.str1.split(' ')))
def Lower(self):
res = list(self.str1)
temp = []
for i in range(len(res)):
if not (ord(res[i]) < 65 or ord(res[i]) > 90):
temp.append(chr(ord(res[i]) + 32))
return ''.join(temp)
def Find(self,target):
i, j = 0,0
length = len(target)
for k in range(len(self.str1)+1):
if self.str1[i:j] == target:
return i
if j >= length:
i += 1
j += 1
return -1
# 没想到好的解法,把一位鱼油的代码搬了过来,简单删减了一下
def Print(*values,sep=None,end=''):
if sep is None:
sep=''
return sep.join((str(i) for i in values))+end
def Str(sth):
return MyStr(sth)
|