python - Python将字符串部分连接到带有分隔符的列表中
问题描述
我有一个字符串列表,['what', 'is', 'apple', '&', 'orange']
仅当 '&' 位于两个字符串之间时才想进行连接。通缉:
['what', 'is', 'apple&orange']
到目前为止我能想到的看起来很愚蠢有没有 Pythonic 的方法来做到这一点?
解决方案
- 这是一个带有字符串方法的 1-liner
l = ['what', 'is', 'apple', '&', 'orange', 'apple', '&', 'banana']
new_list = ' '.join(l).replace(' & ', '&').split()
# print(new_list)
['what', 'is', 'apple&orange', 'apple&banana']
推荐阅读
- git - 从 svn 切换到 git 时构建服务器上的磁盘空间
- android - 可以在 Activity 的构造函数中执行 Dagger 2 注入吗
- python - 无窗口熊猫系列的滚动最小值/累积最小值/扩展最小值
- django - Django 测试 assertTemplate 与包含的模板一起使用
- google-cloud-platform - 从 Google Cloud Composer 中的实例运行代码
- jboss - JBoss CLI 连接到错误的端口,即使它指定的正确
- javascript - 根据 jQuery AJAX 响应中不存在的 ID 删除 div
- c++ - 即使 realloc() 在 C++ 中失败,如何重新分配内存
- c# - 如何在 WPF 中最小化窗口启动时间
- visual-studio-2013 - 如何从 VS2013 .Net Framework 4.8 项目添加对 netstandard 2.0 Nuget 的引用