Reputation: 33
How do I write a function that takes in a string and returns the same string with every pair of odd numbers separated with a dash.
Assume that all characters in the string are numeric.
i.e. "456793" -> "4567-9-3"
Upvotes: 2
Views: 194
Reputation: 106995
from itertools import zip_longest
s = "456793"
print(''.join([a + ('-' if b and int(a) * int(b) % 2 else '') for a, b in zip_longest(s, s[1:])]))
This outputs:
4567-9-3
Upvotes: 1
Reputation: 198436
import re
re.sub(r'(?<=[13579])(?=[13579])', '-', "456793")
# => '4567-9-3'
"Find all places where an odd digit is before and an odd digit is after, and insert a dash."
Upvotes: 3