Ev. Kounis Ev. Kounis - 1 year ago 71
Python Question

Produce a string from a tuple

I am looking for a nice, efficient and pythonic way to go from something like this:

('zone1', 'pcomp110007')

to this:

'ZONE 1, PCOMP 110007'

without the use of
if possible (unless it does make a big difference that is..). So turn every letter into uppercase, put a space between letters and numbers and join with a comma.

What i wrote is the following:

tags = ('zone1', 'pcomp110007')

def sep(astr):
chars = ''.join([x.upper() for x in astr if x.isalpha()])
nums = ''.join([x for x in astr if x.isnumeric()])
return chars + ' ' + nums

print(', '.join(map(sep, tags)))

Which does produce the desired result but looks a bit too much for the task.

The tuple might vary in length but the numbers are always going to be at the end of each string.

Answer Source

My thoughts:

Keep sep a normal function like it is in your original code for readability / maintenance, but also leverage re as suggested in Abdou's answer.

import re
tags = ('zone1', 'pcomp110007')

def sep(astr):
    alpha, num = re.match('([^\d]+)([\d]+)', astr).groups()
    return '{} {}'.format(alpha.upper(), num) 

print(', '.join(map(sep, tags)))

Edit: Note that if you prefer, I think it would also be reasonable to just return:

return alpha.upper() + ' ' + num

Or older style string formatting:

return '%s %s' %(alpha.upper(), num)

Whatever you're most comfortable with.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download