[英]How can I create compress function in Python?
我需要创建一个名为 StringZip 的 function,它通过用重复次数替换重复的字母来压缩字符串。 例如)aaaabbbbbccccccaaaddddd -> a5b5c6a3d5
我想将此代码更改为 function:
s = 'aaaaabbbbbccccccaaaddddd'
result = s[0]
count = 0
for i in s:
if i == result[-1]:
count += 1
else:
result += str(count) + i
count = 1
result += str(count)
print(result)
如何使用 def 创建 function?
西尔! 使用def
创建 function 的方式如下:
def myFunctionName(myParam, myOtherParam):
# your function
return endResult
或者在你的情况下:
# lower_with_under() is the standard for functions in python
def string_zip(inString):
s = inString
result = s[0]
count = 0
for i in s:
if i == result[-1]:
count += 1
else:
result += str(count) + i
count = 1
result += str(count)
print(result)
你会这样称呼它:
theResult = myFunctionName(1, 3)
或者在你的情况下:
print(string_zip("aaaaabbbbbccccccaaaddddd"))
我希望这有帮助!
顺便说一句,下一次,你可以先在 Google 上搜索你想要的东西,然后再在 Stack Overflow 上提问吗? 它有助于保持井井有条。 谢谢!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.