0

I have string like :

8/30/2021 19:22,server1,app1,"user1, Mrs. user2",US,One,Email, Sent,Success

Expected Output :

8/30/2021 19:22|server1|app1|user1, Mrs. user2|US|One|Email| Sent|Success

My code looks like :

....
line = line.replace(',', '|')
print (line)

How to handle double quotes in python using RegEx ?

dmeu
  • 3,842
  • 5
  • 27
  • 43
  • If it's a csv file, I would recommend using a csv module to do it for you. E.g. `pandas.read_csv(file_name).to_csv(sep="|")` – Chris Sep 22 '21 at 12:15

1 Answers1

0

Sorry, my answer is merely a hack, but delivers desired results:

from io import StringIO
import pandas as pd

s = '8/30/2021 19:22,server1,app1,"user1, Mrs. user2",US,One,Email, Sent,Success'
print("|".join(pd.read_csv(StringIO(s)).columns))

Outputs:

'8/30/2021 19:22|server1|app1|user1, Mrs. user2|US|One|Email| Sent|Success'

I kind of would guess though that you could find an answer by googling? :) Or check out the source code of the pandas library!

Update - yes, 5 min of Google Fu revealed the answer! here on SO: https://stackoverflow.com/a/632552/551694 Please go and upvote.

re.sub('(,)(?=(?:[^"]|"[^"]*")*$)','|',s)

delivers

'8/30/2021 19:22|server1|app1|"user1, Mrs. user2"|US|One|Email| Sent|Success'
dmeu
  • 3,842
  • 5
  • 27
  • 43