【发布时间】:2021-12-24 22:31:41
【问题描述】:
我正在寻找一种巧妙的方法来用一个字符串替换多个出现的特定字符。
例如:
我想转换这样的字符串:
string = '1;AA;;1234567;;some text;;some text;;;some text;some text;;;;;;1, 2, 3, 4, 5, 6;;;;;;;;;;;another text;;;;;;;;;;;;;'
到这里:
string = '1;AA;1234567;some text;some text;some text;some text;1, 2, 3, 4, 5, 6;another text;'
其中一种方法是使用基于列表的替换,但它需要制作一个非常庞大的列表,因为后续数据行中重复的数量会有所不同。
所以是这样的:
list = {';;':'';'.';;;'',';':'',';;;;':';',';;;;;':';'} #etc....
input = input.replace(list)
这不是一个好主意。
关于我应该如何进行的任何建议?
问候,
J.
【问题讨论】:
-
试试
string = re.sub(r";+", ";", string) -
谢谢,就是这样:)
标签: python list replace str-replace