Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to replace a char beetween to quote in python

Tags:

python

I have a file with a line like:

1,2,"toto , titi",3"titi ,, tata",4

And I would like to replace each comma , that is beeween quotes (") with a colon :

So my outout should be :

1,2,"toto : titi",3"titi :: tata",4

I am thinking about splitting by " but I think there are betters ways.

like image 693
Bussiere Avatar asked Dec 05 '25 16:12

Bussiere


1 Answers

For this you could use a regex:

import re

string = '1,2,"toto , titi",3"titi ,, tata",4'

print(re.sub('".*?"',  lambda x: x.group().replace(',', ':'), string)) #Output 1,2,"toto : titi",3"titi :: tata",4

The sub method from the re module replaces with the help of a regex.

For the regex, you should use a non greedy pattern .*? to avoid the ,3 being replaced with :3

You can test the regex online

And then I replace with a lambda function by replacing the commas in the matching group by.

like image 101
BlueSheepToken Avatar answered Dec 08 '25 05:12

BlueSheepToken



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!