Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove commas in a string, surrounded by a comma and double quotes / Python

Tags:

python

regex

I've found some similar themes on stackoverflow, but I'm newbie to Python and Reg Exps.

I have a string

,"Completely renovated in 2009, the 2-star Superior Hotel Ibis Berlin Messe, with its 168 air-conditioned rooms, is located right next to Berlin's ICC and exhibition center. All rooms have Wi-Fi, and you can surf the Internet free of charge at two iPoint-PCs in the lobby. We provide a 24-hour bar, snacks and reception service. Enjoy our breakfast buffet from 4am to 12pm on the 8th floor, where you have a fantastic view across Berlin. You will find free car parking directly next to the hotel.",

A pattern should be like: comma, double quote|any text with commas |double quote, comma. I need to replace commas in double quotes, for example with @ character. Which reg exp pattern should I use?

I tried this :

r',"([.*]*,[.*]*)*",' 

with different variations, but it doesn't work.

Thanks for the answers, the problem was solved.

like image 502
Nodari Lipartiya Avatar asked Aug 14 '13 15:08

Nodari Lipartiya


1 Answers

If all you need to do is replace commas with the @ character you should look into doing a str_replace rather than regex.

str_a = "Completely renovated in 2009, the 2-star Superior Hotel Ibis Berlin Messe, with its 168 air-conditioned rooms, is located right next to Berlin's ICC and exhibition center. All rooms have Wi-Fi, and you can surf the Internet free of charge at two iPoint-PCs in the lobby. We provide a 24-hour bar, snacks and reception service. Enjoy our breakfast buffet from 4am to 12pm on the 8th floor, where you have a fantastic view across Berlin. You will find free car parking directly next to the hotel."

str_a = str_a.replace('","', '@') #commas inside double quotes
str_a = str_a.replace(',', '@') #replace just commas

print str_a

Edit: Alternatively you could make a list of what you want to replace, then loop through it and perform the replacement. Ex:

to_replace = ['""', ',', '"']

str_a = "Completely renovated in 2009, the 2-star Superior Hotel Ibis Berlin Messe, with its 168 air-conditioned rooms, is located right next to Berlin's ICC and exhibition center. All rooms have Wi-Fi, and you can surf the Internet free of charge at two iPoint-PCs in the lobby. We provide a 24-hour bar, snacks and reception service. Enjoy our breakfast buffet from 4am to 12pm on the 8th floor, where you have a fantastic view across Berlin. You will find free car parking directly next to the hotel."

for a in to_replace:
    str_a = str_a.replace(a, '@')

print str_a
like image 195
Peter Foti Avatar answered Sep 28 '22 06:09

Peter Foti