trying to replace <strong>comma</strong> between 2 words <strong>Durango and PC</strong> in the second line by <strong>&</strong> and then remove the quotes " as well. Same for third line with <strong>Orbis and PC</strong> I would like to retain the rest of the lines using Python:
2,SIN-Rendering,Core Tech - Rendering,PC,147,Reopened 2,Kenny Chong,Core Tech - Rendering,"Durango, PC",55,Reopened 3,SIN-Audio,AAA - Audio,"Orbis, PC",13,Open ... ... ...
Like these, there can be 100 lines in my sample. So the expected output is:
2,SIN-Rendering,Core Tech - Rendering,PC,147,Reopened 2,Kenny Chong,Core Tech - Rendering, Durango & PC,55,Reopened 3,SIN-Audio,AAA - Audio, Orbis & PC,13,Open ... ... ...
So far, I could think of reading line by line and then if the line contains quote replace it with no character but then replacement of symbol inside is something I am stuck with.
How to achieve this, any suggestion? Learning Python.Answer1:
Use a <a href="https://docs.python.org/3/library/re.html" rel="nofollow">regular expression</a> for this. Write a regular expression that catches your string, and then use it to replace it.
It should look something like this:
This will catch your <em>Durango</em> and <em>PC</em>, and map both of them into two groups which you later use when you replace them.Answer2:
Something like this? Add proper
if() if you want to switch comma to ampersand only in second line:
This code goes trough all lines with
..., "..., ...", ... =>
..., ... & ..., ...
import re expr = r'2,Kenny Chong,Core Tech - Rendering,"Durango, PC",55,Reopened' expr2 = re.findall('"(.*?)"', expr) if len(expr2)!=0: expr3 = re.split('"',expr) expr4 = expr3+expr3.replace(","," &")+expr3 print(expr4)Answer3:
Something like below:
st = "2,Kenny Chong,Core Tech - Rendering,\"Durango, PC\",55,Reopened" res = re.sub(r'\"(.*),\ (.*)\"',lambda x : (" & ").join(re.findall(r'\"(.*),\ (.*)\"', st)),st)