Home > Software design >  Blender Python String manipulation
Blender Python String manipulation

Time:11-08

How do you remove all characters except the array of float values and sepparators(,)?

<Color (r=0.65, g=0.54, b=0.43)>

Into this: 0.65, 0.54, 0.43

CodePudding user response:

using regexps:

import re
nre = re.compile(r'*.(0\.\d\d).*(0\.\d\d).*(0\.\d\d)')
m = nre.match('<Color (r=0.65, g=0.54, b=0.43)>')
print(' ,'.join(m.groups()))
==> 0.65 ,0.54 ,0.43

CodePudding user response:

You can use regex like re.findall to extract all float numbers from the string then use str.join to add ', ' between numbers.

>>> import re
>>> ', '.join(re.findall("\d \.\d ", "<Color (r=0.65, g=0.54, b=0.43)>"))
'0.65, 0.54, 0.43'

Explanation:

  • \d : Matches any digit character (0-9). Equivalent to [0-9].
    • : Matches 1 or more of the preceding token.
  • \. : Matches a "." character.

If you want to get numbers as a list of float.

>>> re.findall("\d \.\d ", "<Color (r=0.65, g=0.54, b=0.43)>")
['0.65', '0.54', '0.43']

>>> list(map(float, re.findall("\d \.\d ", "<Color (r=0.65, g=0.54, b=0.43)>")))
[0.65, 0.54, 0.43]
  • Related