I want to replace a space to underscore, if the space is in between double quotes. Example:
given = 'hello "welcome to" python "blog"'
expected = 'hello "welcome_to" python "blog"'
My actual string is in SQL code and I need to transform it to use underscore for migration purpose.
What I tried
import re
s = 'hello "welcome to" java 2 "blog"'
a = re.sub('(\"[\w\s] \")', '_', s)
print (a)
Also been trying and trying to google but can't find yet.
How to do in Python?
CodePudding user response:
If you aren't forced to use regex, don't, because that's not a good option here.
inp = 'hello "welcome to" python "blog"'
data = inp.split('"')
for i, part in enumerate(data[:-1]):
if i % 2 == 1:
data[i] = part.replace(' ', '_')
out = '"'.join(data)
print(out)
'hello "welcome_to" python "blog"'
You can do this with a list comprehension if you want, but it looks worse imo
'"'.join(s if i % 2 == 0 else s.replace(' ', '_') for i, s in enumerate(inp.split('"')))
or formatted
'"'.join(
s if i % 2 == 0
else s.replace(' ', '_')
for i, s in enumerate(inp.split('"')[:-1])
)
CodePudding user response:
Well I think you can use the loop for iterate your string and generate new string with the char of source string (change it when you found space between double quotes). But the bad side of my solution is a creating a new string every iteration.
given = 'hello "welcome to" python "blog"'
double_quote = False
expected = ''
for c in given:
if double_quote:
if c == ' ':
c = '_'
elif c == '"':
double_quote = False
elif c == '"':
double_quote = True
expected = c
print(expected)
Maybe we can optimize my code within a list
given = 'hello "welcome to" python "blog"'
double_quote = False
expected = []
for c in given:
if double_quote:
if c == ' ':
c = '_'
elif c == '"':
double_quote = False
elif c == '"':
double_quote = True
expected.append(c)
expected = ''.join(expected)