python-3.x - 用列表替换多个字符串
问题描述
我正在尝试使用列表从单个文本字符串中删除多个项目。
这是解决方案的开始:
tmp_text = 'Mr. Random Name'
replace = ['Mr. ', 'Ms. ','Prof. ']
tmp_text = [tmp_text.replace(r, '') for r in replace]
但是,我想返回一个文本字符串,其中删除了列表“替换”中的所有项目。上面返回三个字符串:['Random Name', 'Mr. 随机名字','先生。随机名称']
解决方案
在循环中替换:
for r in replace:
tmp_text = tmp_text.replace(r, "")
或者使用正则表达式:
tmp_text = re.sub("|".join(replace), "", tmp_text)
推荐阅读
- css - 使用 CSS 样式表更改闪亮的“确定”按钮 (confirmButtonCol) 的颜色
- android - 如何让手机模拟器运行手机应用程序而不佩戴操作系统应用程序?
- python - 为什么我的 ChoiceField 没有从我的 Django 表单呈现到模板上?
- javascript - 如何在需要时替换 debounceTime(0) 发射?
- sql - 通过 Azure 流分析作业使用时间戳时未写入数据
- firebase - 未处理的异常:'package:flutter/src/widgets/navigator.dart':断言失败:'!navigator._debugLocked':不正确
- javascript - jQuery - 如何在下拉值更改时在 Kendo Grid 内的 Kendo DatePicker 上设置今天的日期
- java - 我无法获得所有节点的平均值以用 Java 打印
- python - 如何从两个列表中获取字典可能性的每个排列?
- python - 找不到来自 pyinstaller“spec”文件的“datas”数组中的文件