Replace line number with brackets with Python number

I have a line like this:

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

I want to convert this so that every number that follows the letter ( khere) is 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 this?

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

+4
source share
2 answers

Here is one of the options with the help of rethe regular expression module ([a-zA-Z])(\d+), which corresponds to one letter, followed by numbers and sub, you can enclose coincident numbers with two brackets in 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'

, , :

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'
+5

?

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

Source: https://habr.com/ru/post/1667441/


All Articles