2

I am looking for a Python expression that would transform this chunk of text:

z= 10
zi = 300
print(z)
print(z * 180)
print(z - 3241)
y=z
print(type(z))
print(type(y))
print(type(z[0]))
print(type(z[1]))

into the following chunk of text:

K= 10
zi = 300
print(K)
print(K * 180)
print(K - 3241)
y=K
print(type(K))
print(type(y))
print(type(K[0]))
print(type(K[1]))

I have tried:

newdata = filedata.replace("z", "K")

But, this replaces all instances of z, whereas I would only like to replace words whose only letters are z.

Sean Pianka
  • 2,157
  • 2
  • 27
  • 43
jason
  • 3,932
  • 11
  • 52
  • 123

1 Answers1

2

This can easily be achieved through the use of regular expression word boundaries (the \b seen before and after the target string z as the first argument to re.sub): What is a word boundary in regexes?

import re
newdata = re.sub(r"\bz\b", "K", filedata)
print(newdata)

The output of printing newdata will be:

K= 10
zi = 300
print(K)
print(K * 180)
print(K - 3241)
y=K
print(type(K))
print(type(y))
print(type(K[0]))
print(type(K[1]))
Sean Pianka
  • 2,157
  • 2
  • 27
  • 43
  • 1
    You beat me to it, but I used: `r'\bz\b'` for my RE (imagine "buzz"). Possibly helpful t give the meaning of `\b`? – cdarke May 13 '18 at 21:35
  • @cdarke Good point. I was targeting their specific input case, but surrounding the `z` with word boundaries would ensure this worked with any input. – Sean Pianka May 13 '18 at 21:38
  • I'm trying to use it in a for loop but it is not working in a for loop but it works as a standalone text. I've tried the code below. **new_val = r'\b{0}\b'.format(value) # newval = r"\b" + (value) + r"\b"** – jason May 14 '18 at 09:12