Joshua Edwin
Joshua Edwin

Reputation: 33

Find odd pair in string of integers using python

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

Answers (2)

blhsing
blhsing

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

Amadan
Amadan

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

Related Questions