gpt4 book ai didi

python - 对Python中不可变的字符串: how to,进行多次修改?

转载 作者:行者123 更新时间:2023-12-01 05:54:26 24 4
gpt4 key购买 nike

我是 Python 新手,所以也许我要求一些非常简单的东西,但我无法以 Python 的方式思考问题。

我有一个压缩字符串。这个想法是,如果一个角色重复 4-15 次,我会进行以下更改:

'0000' ---> '0|4'

如果超过 15 次,我使用斜线和两位数字来表示金额(使用十六进制值):

'00...(16 times)..0' ---> '0/10'

因此,习惯了其他语言,我的方法如下:

def uncompress(line):
verticalBarIndex = line.index('|')
while verticalBarIndex!=-1:
repeatedChar = line[verticalBarIndex-1:verticalBarIndex]
timesRepeated = int(line[verticalBarIndex+1:verticalBarIndex+2], 16)
uncompressedChars = [repeatedChar]
for i in range(timesRepeated):
uncompressedChars.append(repeatedChar)
uncompressedString = uncompressedChars.join()
line = line[:verticalBarIndex-1] + uncompressedString + line[verticalBarIndex+2:]
verticalBarIndex = line.index('|') #next one

slashIndex = line.index('/')
while slashIndex!=-1:
repeatedChar = line[slashIndex-1:slashIndex]
timesRepeated = int(line[slashIndex+1:verticalBarIndex+3], 16)
uncompressedChars = [repeatedChar]
for i in range(timesRepeated):
uncompressedChars.append(repeatedChar)
uncompressedString = uncompressedChars.join()
line = line[:slashIndex-1] + uncompressedString + line[slashIndex+3:]
slashIndex = line.index('/') #next one
return line

我知道这是错误的,因为字符串在 Python 中是不可变的,而且我一直在更改行内容,直到没有“|”为止或“/”存在。

我知道 UserString 存在,但我想有一种更简单、更 Python 的方式来实现它,这非常值得学习。

有什么帮助吗?

最佳答案

使用示例字符串运行代码所需的更改:

.index()更改为.find()。如果未找到子字符串,.index() 会引发异常,.find() 返回 -1。

uncompressedChars.join() 更改为 ''.join(uncompressedChars)

timesRepeated = int(line[slashIndex+1:verticalBarIndex+3], 16) 更改为 timesRepeated = int(line[slashIndex+1:slashIndex+3], 16)

设置 uncompressedChars = [] 开始,而不是 uncompressedChars = [repeatedChar]

这应该可以让它正常工作。有很多地方需要对代码进行整理和优化,但是这是可行的。

关于python - 对Python中不可变的字符串: how to,进行多次修改?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13157677/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com