Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace number in a string by bracketed number Python

I have a string like this:

s = k0+k1+k1k2+k2k3+1+12

I want to convert this, such that every number, which follows a letter (k here) becomes surrounded by square brackets:

k[0]+k[1]+k[1]k[2]+k[2]k[3]+1+12

What is a good way to do that?

What I tried: Use replace() function 4 times (but it cannot handle numbers not followed by letters).

like image 351
hola Avatar asked Mar 11 '23 02:03

hola


1 Answers

Here is one option using re module with regex ([a-zA-Z])(\d+), which matches a single letter followed by digits and with sub, you can enclose the matched digits with a pair of brackets in the replacement:

import re
s = "k0+k1+k1k2+k2k3+1+12"

re.sub(r"([a-zA-Z])(\d+)", r"\1[\2]", s)
# 'k[0]+k[1]+k[1]k[2]+k[2]k[3]+1+12'

To replace the matched letters with upper case, you can use a lambda in the replacement positions to convert them to upper case:

re.sub(r"([a-zA-Z])(\d+)", lambda p: "%s[%s]" % (p.groups(0)[0].upper(), p.groups(0)[1]), s)

# 'K[0]+K[1]+K[1]K[2]+K[2]K[3]+1+12'
like image 193
Psidom Avatar answered Mar 12 '23 22:03

Psidom