Regular Expressions
You can do this with regular expressions:
([02468]{2,})
Captures any sequence formed by the numbers 0, 2, 4, 6 or 8 with two or more of size. After capturing the sequences of even numbers just replace by itself by adding the hyphen:
'-'.join(grupo_capturado) # '-'.join('28') = '2-8'
So the code stays:
import re
def adiciona_separador(matches):
return '-'.join(matches.group(0))
resultado = re.sub(r'([02468]{2,})', adiciona_separador, '02368859')
print(resultado) # 0-236-8-859
If you want to do a function for that:
def separador(numero, separador='-'):
return re.sub(
r'([02468]{2,})',
lambda matches: separador.join(matches.group(0)),
numero
)
print( separador('02368859') ) # 0-236-8-859
See working on Repl.it | Ideone
Forma Iterativa
Iteratively, as you tried to do, you can go directly through the string, do not need to convert it to a list. In Python strings are iterable as well. You can iterate over the characters in this string adding them into a string and whenever you find an even number you check whether the last value of this string is also even, if yes, you add a hyphen before adding the current number.
def separador(entrada):
resultado = ''
for caractere in entrada:
if caractere in '02468':
if len(resultado) > 0 and resultado[-1] in '02468':
resultado += '-'
resultado += caractere
return resultado
print(separador('02368859')) # 0-236-8-859
See working on Repl.it | Ideone
Okay, I’ll study her here. Thank you very much Anderson.
– Rafaelcvo
Ball show! :)
– Éder Garcia
You got practically on a command line, congratulations. I see I have to study hard yet.
– Rafaelcvo
@Rafaelm. I’ve added a shape that’s basically what you’ve done, only a more streamlined form.
– Woss
I was analyzing and lacked a little more logic in mine. This yours became simple and good.
– Rafaelcvo
If I were to do this exercise, my initial attempt would be similar to your approach with regex, but using Lookahead to insert the hyphens. Example:
re.sub(r'([02468])((?=([02468])))', r'\1-\2', '02368859')
– Gabriel
@Gabriel Does not want to post this alternative as an answer?
– Woss
@Andersoncarloswoss Feito.
– Gabriel