欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Python 第一式

程序员文章站 2022-08-20 14:07:25
@Codewars Python练习 question Dashatize it Given a number, return a string with dash' 'marks before and after each odd integer, but do not begin or end ......

@codewars python练习

question

** dashatize it **

given a number, return a string with dash'-'marks before and after each odd integer, but do not begin or end the string with a dash mark.

ex:

dashatize(274) -> '2-7-4'
dashatize(6815) -> '68-1-5'

solutions

my solutions

def dashatize(num):
    l2 = [ ]
    if num == none:
        return 'none'
    else:
         # 将字符串抓为数字存为数组l2
        l = list(str(num))
        for i in range(len(l)):
            if l[i] != '-':
                l[i] = int(l[i])
                l2.append(l[i])
        # 将分配字符和符号存为数组l3 
        l3 = [l2[0],]
        for  i in range(1, len(l2)):
            if l2[i] % 2 == 0 and l2[i-1] % 2 != 0:
                l3.append('-')
                l3.append(l2[i])
            elif l2[i] % 2 != 0:
                l3.append('-')
                l3.append(l2[i])
            else:
                l3.append(l2[i])  
        c = map(str,l3)
      
        return "".join(c)

other solutions

import re
def dashatize(num):
    try:
        return ''.join(['-'+i+'-' if int(i)%2 else i for i in str(abs(num))]).replace('--','-').strip('-')
    except:
        return 'none'

[========]

  • 学习re表达式
  • 多认识库并导入使用