Skip to content Skip to sidebar Skip to footer

Python String.replace Alternative

I need help with Python string manipulation (I boiled down my previous looong question to this issue below). For this line from a file: L20B, CVS=1, HTYP=16, MLV=25 The second fie

Solution 1:

Use regular expressions:

import re
re.sub(r'(C|)VS=.*', r'\1FIXD(0,1,0)', line)

Explanation:

# regex
  (C|)         # optionally match a 'C', save it or an empty string ingroup1
  VS=          # match'VS='
  .*           # matchto the endof the line

# replacement
  \1           # the contents ofgroup1 (either 'C'or an empty string)
  FIXD(0,1,0)  # the literal string 'FIXD(0,1,0)'

Examples:

>>> re.sub(r'(C|)VS=.*', r'\1FIXD(0,1,0)', 'L20B, CVS=1, HTYP=16, MLV=25')
'L20B, CFIXD(0,1,0)'>>> re.sub(r'(C|)VS=.*', r'\1FIXD(0,1,0)', 'L20C, VS=4, HTYP=9, MLV=5')
'L20C, FIXD(0,1,0)'

Edit: based on your edit here are a few alternatives for your different cases:

  • CVS or VS -> CFIXD(0,1,0) or FIXD(0,1,0)

    re.sub(r'(C|)VS=.*', r'\1FIXD(0,1,0)', line)
    
  • CRH or RH -> CVR(0,1,0) or VR(0,1,0)

    re.sub(r'(C|)RH=.*', r'\1VR(0,1,0)', line)
    
  • CFIXD(x,y,z) or VIXD(x,y,z) -> CVR(x,y,z) or VR(x,y,z)

    re.sub(r'(C|)FIXD(\([^)]*\)).*', r'\1VR\2', line)
    

Explanation of (\([^)]\)).*:

(         # startsecond capture group
   \(       # match a literal '('
   [^)]*    # matchany number of characters that arenot')'
   \)       # match a literal ')'
)         # end capture group
.*        # matchto the endof the line

Solution 2:

You can use a regular expression, but to me it'd be more straightforward to just split the string into a list:

line = "L20B, CVS=1, HTYP=16, MLV=25"

line = line.split(", ")
if line[1].startswith("CVS="):
    line[1:] = ["CFIXD(0,1,0)"]
elif line[1].startswith("VS="):
    line[1:] = ["FIXD(0,1,0)"]

line = ", ".join(line)

These two cases could be combined with some jiggery-pokery, since they are rather similar, but they seem perfectly readable this way.

Post a Comment for "Python String.replace Alternative"