问题给出了一个‘压缩后’的文字,要求输出一个解压后的文字。
如:输入hel(-1)o,输出hello。
(-1)是指代前一位重复出现过的字母,如图所示
由于只学过入门的for循环和index的切片等操作。我尝试用i.isdigit()找到字符串里的数字,然后定位它的index,但是如果出现了一样的数字定位就会有问题
求大家帮助~谢谢
Text to decompress? hel(-1)o
hello
Text to decompress? a(-1)rdv(-4)(-4)k
aardvark
Text to decompress? The cat(-4)in(-3)(-5)(-11)(-11)(-4)(-3)(-11)(-6)
The cat in the hat
decompress = list(input('Text to decompress?'))
output = ''
flag = 0
thechar = ''
theint = 0
for i,value in enumerate(decompress):
if value == '(':
flag = 1
continue
if value == '-' and flag == 1:
flag = 2
continue
if value == ')' and flag == 2:
flag = 0
output += output[ len(output) - theint]
theint = 0
continue
if flag == 2:
theint = theint * 10 + int(value)
continue
if flag == 0:
output += value
print(output)
朋友,这是对字符串的基本处理,python里有很多很多函数可以实现这些操作。
我帮你写了一个,你可以参考下,虽然我写的哈哈哈哈,很麻烦
我的方法发是:
1.提取()中的数字,存在cindex的list中
2.提取字符串的每一个字符,去除()以及其中的数字,用一个标识来代替他的位置,我用的标识是“index”,将提取的字符和标识存在character这个list中
3.按顺序遍历一遍character,遇到标识“index”就用cindex指向的字符来代替这个标识
4.将list转化为字符串输出
def decompress(string):
cindex=[] #存解压时的引索
temp=string.split('(')#用split函数分割输入的句子
character=[]#存放每一个字符
for i in range(len(temp)):#上一步分割了(,还需要分割),这个循环可以实现
if ')'in temp[i]:
cindex.append(temp[i].split(')')[0])#分割),把分割结果存好
character.append('index')#每次遇到(数字)就用标识“character”代替
temp2=temp[i].split(')')[1]
temp4=list(temp2)
for j in range(len(temp2)):#继续提起)后面的每一个字符
character.append(list(temp4)[j])
else:#没有遇到(或者)时,上面的操作就简化为一下操作
temp2=list(temp[i])
for j in range(len(temp2)):
character.append(temp2[j])
j=0
for i in range(len(character)):#这个循环用实现你这里的解压
if character[i]=='index':
character[i]=character[i+eval(cindex[j])]
j=j+1
outstring=''.join(character)#这里将最后的结果拼接为字符串,然后输出即可
print(cindex)
print(outstring)
temp=string.split
if __name__=="__main__":
inputs="The cat(-4)in(-3)(-5)(-11)(-11)(-4)(-3)(-11)(-6)"
decompress(inputs)