F
F
fantom_ask2020-04-24 13:40:02
Python
fantom_ask, 2020-04-24 13:40:02

How to change an arbitrary parameter after a specific word in a string?

I have a string

text = 'background:red;border-color:rgba(255,255,255,0);color:#0ff;'

and I want to change the value in it after the word color but I'm not good at regular expressions The only thing I came up with is
print(re.findall(r'\w+', text))
for x in self.rad.styleSheet().split(';') :
  valx = x.split(':')
  #print(valx)
  X_1 = valx[0]
  try: 
    X_2 = valx[1]
  except:
    X_2 = None
  if valx[0] == "color" :
    X_2 = "blue"
  
  if not X_2 == None :
    string = string + X_1 + ":" + X_2 + ";"
print(string)

Answer the question

In order to leave comments, you need to log in

1 answer(s)
I
Ivan Yakushenko, 2020-04-24
@fantom_ask

If the string template is always the same, without exceptions, then it is possible without regular expressions:

In [1]: text = 'background:red;border-color:rgba(255,255,255,0);color:#0ff;'

In [2]: text = text[:text.find(';color:')] + '#FFFFF;'

In [3]: text
Out[3]: 'background:red;border-color:rgba(255,255,255,0)#FFFFF;'

Using a regular expression:
In [1]: import re

In [2]: text = 'background:red;border-color:rgba(255,255,255,0);color:#0ff;'

In [3]: to_replace = '#FFFFF'

In [4]: text = text.replace(re.search(r'(^|[^-])color:(.*?)\;', text).group(2), to_replace)

In [5]: text
Out[5]: 'background:red;border-color:rgba(255,255,255,0);color:#FFFFF;'

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question