-2

I am trying to use python code to replace the character value 'K' with 'M' in the following code snippet, but not having much luck.

code:

import re

original_text = 'context PQ-4662-33-K64C-C-DDxxx-Sxxxx'
regex = re.compile(r'context\s.*\d[0-9]\-\w\w\-(K).*')
result = re.match(regex, original_text)
replace_attempt = regex.sub(r'M\1', original_text)

print(result.group(0))
print(result.group(1))
print(replace_attempt)

output:

context PQ-4662-33-K64C-C-DDxxx-Sxxxx
K
MK

Process finished with exit code 0

The desired output I am seeking:

context PQ-4662-33-M64C-C-DDxxx-Sxxxx
mad_
  • 7,475
  • 1
  • 18
  • 32
zeepi
  • 33
  • 1
  • 7
  • Does `original_text.replace('K', 'M')` help? If not, you are going to need to add more on why you need to replace what you need. – Austin Oct 10 '18 at 15:11
  • `re.sub('K','M',original_text)` ?? – mad_ Oct 10 '18 at 15:11
  • does this have to be done with regex? – vash_the_stampede Oct 10 '18 at 15:19
  • Please provide more context to this question. It's incredibly vague. Are you attempting to replace all 'K's with 'M's? Are you attempting to replace any character at the Nth position with 'M'? Are you doing the previous, but only if the Nth item is a 'K'? etc, etc. Please be more specific. – Julian Oct 10 '18 at 15:34

2 Answers2

1

Replace with required groups

original_text = 'context PQ-4662-33-K64C-C-DDxxx-Sxxxx'
original_text=re.sub(r'(context\s.*\d[0-9]\-\w\w\-)(K)(.*)',r'\1'+'M'+r'\3',original_text)
print(original_text) #'context PQ-4662-33-M64C-C-DDxxx-Sxxxx'

If you simply want to replace all `K with M

re.sub('K','M',original_text)
mad_
  • 7,475
  • 1
  • 18
  • 32
0

If all you want to do is replace K with M, then you can simply do either:

1) re.sub('K', 'M', original_text)

2) original_text.replace('K', 'M')

Both will yield:

context PQ-4662-33-M64C-C-DDxxx-Sxxxx

If your requirements are more specific, and the input strings always follow a prescribed pattern:

re.sub(r'(?<=context [A-Z]{2}-\d{4}-\d{2}-)[A-Z]', 'M', original_text)

Again yields:

context PQ-4662-33-M64C-C-DDxxx-Sxxxx
rahlf23
  • 7,918
  • 3
  • 14
  • 44