我试图创建修剪字符和修剪字符串的功能。我知道我可以使用python的内置函数,但是我试图制作这些函数以便我能理解它是如何工作的。
#Trim Character
def trim_chr(op1,op2):
"""Returns of a copy of the first parameter, where all leading and \
trailing instances of the second parameter have been removed. Returns\
unaltered copy of the first parameter if the second parameter is not\
of length 1"""
finalword=""
if len(op2) != 1:
return op1
for i in op1:
if i != op2:
finalword+=i
for i in op1[::-1]:
if i!=op2:
break
return finalword
print("trim_chr")
h=trim_chr("zzapplezz","z")
print(h)
苹果
h1=trim_chr("aa+=Baloon+=aaaaa","a")
print(h1)
+ = +的bloon =
我想要的输出是:+ = Baloon + =
h2=trim_chr("ZZappleZZ","zz")
print(h2)
h3=("HelloWorld","")
print("")
ZZappleZZ
我想要的h1输出是+ =气球+ =。我只想摆脱前面和后面的字符而不是中间的字符。
我还确定删除尾随或结束字符串,而不仅仅是单个字符,与此函数类似。我该怎么办呢?
答案 0 :(得分:1)
答案 1 :(得分:1)
当您找到第一个非op2字符时,您需要退出第一个循环。如上所述,您将保留在循环中以复制其余部分,但这意味着您还将停留在删除op2字符的循环中。更容易这样:
for i in range(len(op1)):
if op1[i] != op2:
finalword = op1[i:]
break
if (not finalword): return("") # never found non-op2
while finalword[-1] == op2:
finalword = finalword[0:-1]
return finalword
如果您想使用大于1个字符的“op2”值,您可以执行以下操作:
finalword = op1
while finalword.startswith(op2):
finalword = finalword[len(op2):]
while finalword.endswith(ops):
finalword = finalword[0:-len(op2)]
return finalword
答案 2 :(得分:0)
那个怎么样
def trim_chr(op1,op2):
#copy op1 so you can work on the copy but still have the original to work with
finalword = op1[:]
#loop from the begining and remove the matching characters
for i in op1:
if i == op2:
finalword = finalword[1:]
else:
break
#loop from the end and remove the matching characters
for i in op1[::-1]:
if i == op2:
finalword = finalword[:-1]
else:
break
#return the finalword
return finalword
还有其他实现的课程,但是这个实现与你的for循环匹配,但不是像你一样建立一个新的字符串,我只是复制op1并只从中移除