Python转换字符串格式

本文阅读 1 分钟
首页 Python笔记 正文

转换字符串格式为原来字符串里的字符+该字符连续出现的个数
例如1233422222, 转化为1121324125

  1. def convertString(string):
  2. if string == None or len(string) <= 0:
  3. return
  4. outputStr = ""
  5. length = len(string)
  6. index = 0
  7. while index < length:
  8. count = 0
  9. while index+count < length and string[index] == string[index+count]:
  10. count += 1
  11. outputStr += string[index] + str(count)
  12. index += count
  13. return outputStr
  14. # 可以用来判断字符串标识的函数, 比如Mississippi转化为"i4m1p2s4"
  15. # 这里讲次数出现1次的省去, Mississippi转化为"mi4s4p2"
  16. def convertString2(string):
  17. if string == None or len(string) <= 0:
  18. return
  19. string.lower()
  20. outputStr = ""
  21. dictSet = {}
  22. for i in string:
  23. if i not in dictSet.keys():
  24. dictSet[i] = 0
  25. dictSet[i] += 1
  26. for i in string:
  27. if i in outputStr: continue
  28. outputStr += (i + str(dictSet[i])) if dictSet[i] != 1 else i
  29. return outputStr
  30. print(convertString("1233422222"))
  31. print(convertString("a"))
  32. print(convertString2("mississippi"))
解压密码: detechn或detechn.com

免责声明

本站所有资源出自互联网收集整理,本站不参与制作,如果侵犯了您的合法权益,请联系本站我们会及时删除。

本站发布资源来源于互联网,可能存在水印或者引流等信息,请用户自行鉴别,做一个有主见和判断力的用户。

本站资源仅供研究、学习交流之用,若使用商业用途,请购买正版授权,否则产生的一切后果将由下载用户自行承担。

Python正方体对面和相同
« 上一篇 01-21
Python输出连续质数序列
下一篇 » 01-21

发表评论

惪特博客
  • 文章总数:
    18497 篇
  • 评论总数:
    53318 条
  • 标签总数:
    8873 个
  • 总浏览量:
    22617230 次
  • 最后更新:
    4天前

最多点赞

随便看看

标签TAG