如何在Python中创建压缩函数?

2024-10-03 00:16:20 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要创建一个名为StringZip的函数,该函数通过用重复数替换重复的字母来压缩字符串。Ex)AAAAA BBBBB中交AAADDD->;a5b5c6a3d5

我想将此代码更改为函数:

 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创建函数


Tags: 函数字符串代码gtcount字母resultex
1条回答
网友
1楼 · 发布于 2024-10-03 00:16:20

西尔!使用def创建函数的方法如下:

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上询问它?它有助于保持组织。谢谢

相关问题 更多 >