python-3.x - 在字符串中第二次出现特定字符后删除文本 - 有更好的方法吗?
问题描述
在此示例中,我想删除第二个逗号后的文本。string = "这是字符串,删除第二个逗号后的文本,将被删除。"
我想出了这个解决方案:
text = "This is string, remove text after second comma, to be removed."
k= (text.find(",")) #find "," in a string
m = (text.find(",", k+1)) #Find second "," in a string
new_string = text[:m]
print(new_string)
它有效,但如何以更 Pythonic 的方式制作它?
解决方案
我想这就是你要找的:
text = "This is string, remove text after second comma, to be removed."
print(''.join(text[:[pos for pos, char in enumerate(text) if char == ','][1]+1]))
推荐阅读
- sql - Google Big Query 上的专利公开数据:专利数据集多久更新一次?
- c# - ASP.NET CORE 2.2 ( & 3.x) WEB API 使用 Razor 引擎生成报告
- css - 背景图像未出现在 github 页面上
- powershell - 查找包含“string_a”的行,然后替换匹配的“string_b”
- java - 当我使用 Java Access Bridge 捕获元素时,我无法获取元素的父级;
- python - Django 管理站点 change_list 视图自定义
- session - 如何绕过在 vbScript 或 VBA 代码中对主机会话 ID 进行硬编码
- python - 使用 Ctypes 将 Numpy 数组传递给 C 在 Linux 和 Windows 之间有所不同
- webpack - Webpack - 构建中缺少图像
- javascript - ReactJS - 当弹出按钮被按下并进入错误页面时系统重新呈现(我没有给出任何命令来发生这种情况)