Python 第一式
@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表达式
- 多认识库并导入使用
企鹅号:1272420336,一起学习,一起进步~