gpt4 book ai didi

python - 去除字符串中的逗号,用逗号和双引号包围/Python

转载 作者:太空狗 更新时间:2023-10-29 21:40:14 28 4
gpt4 key购买 nike

我在 stackoverflow 上发现了一些类似的主题,但我是 Python 和 Reg Exps 的新手。

我有一个字符串

,"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.",

模式应该是这样的:comma, double quote|any text with commas |double quote, comma。我需要用双引号替换逗号,例如 @ 字符。我应该使用哪种正则表达式模式?

我试过这个:

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

有不同的变体,但它不起作用。

感谢解答,问题已解决。

最佳答案

如果您需要做的只是用 @ 字符替换逗号,您应该考虑使用 str_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."

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

print str_a

编辑:或者,您可以列出要替换的内容,然后遍历它并执行替换。例如:

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

关于python - 去除字符串中的逗号,用逗号和双引号包围/Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18235923/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com