python - 在Python中用一个字符替换字符串中的多个字符
问题描述
我正在寻找一种巧妙的方法来用一个字符串替换多个出现的特定字符。
例如:
我想转换这样的字符串:
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。
解决方案
使用split()
,列表理解和join()
string = '1;AA;;1234567;;some text;;some text;;;some text;some text;;;;;;1, 2, 3, 4, 5, 6;;;;;;;;;;;another text;;;;;;;;;;;;;'
x = string.split(';') # returns a list with '' instead of the repeating ';'
x = [i for i in x if i] # deletes the '' from the list
y = ';'.join(x) # join back the list to a string separated by ';'
print(y)
或者
string = ';'.join([i for i in string.split(';') if i])
推荐阅读
- javascript - JavaScript 无法正确检测页面上的元素
- oracle - 甲骨文和 GitLab
- camunda - 如何获取与特定任务的 processInstanceId 关联的 ProcessBusiness 键?
- arrays - MongoDB:根据位置范围更新数组的子集
- matlab - 线性规划求解器中上限和下限的参数
- reactjs - SyntaxError:无法在模块 React 路由器之外使用 import 语句
- java - Java 上的 LRU 项目
- php - Laravel 伪造者工厂
- c++ - G++ 编译器找不到 iostream 所需的标头
- json - 在同一文件夹级别的 JSON 文件上导入错误 - 打字稿