hola
hola

Reputation: 950

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).

Upvotes: 4

Views: 1175

Answers (2)

akuiper
akuiper

Reputation: 214957

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'

Upvotes: 6

Shiping
Shiping

Reputation: 1327

How about this?

s = re.sub('([a-z]+)([0-9]+)', r"\1" + '[' + r"\2" + ']', s)

Upvotes: 2

Related Questions