python - 按特定字母拆分字符串,同时将它们保留在字符串中

标签 python

我正在尝试按特定字母(在本例中为:'r'、'g' 和'b')拆分字符串,以便稍后将它们附加到列表中。这里要注意的是,我希望这些字母也被复制到列表中。

string = '1b24g55r44r'

我想要的:

[[1b], [24g], [55r], [44r]]

最佳答案

您可以使用 findall :

import re

print([match for match in re.findall('[^rgb]+?[rgb]', '1b24g55r44r')])

输出

['1b', '24g', '55r', '44r']

正则表达式匹配:

  • [^rgb]+? 所有不是 rgb 一次或多次
  • 后跟 [rgb] 之一。

如果您需要结果是单例列表,您可以这样做:

print([[match] for match in re.findall('[^rgb]+?[rgb]', '1b24g55r44r')])

输出

[['1b'], ['24g'], ['55r'], ['44r']]

此外,如果字符串仅由 digitsrgb 组成,您可以这样做:

import re

print([[match] for match in re.findall('\d+?[rgb]', '1b24g55r44r')])

上述正则表达式中唯一的变化是\d+?,这意味着匹配一个或多个数字。

输出

[['1b'], ['24g'], ['55r'], ['44r']]

关于python - 按特定字母拆分字符串,同时将它们保留在字符串中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52344910/

相关文章:

python - 如何在 Selenium python firefox 中启用 flash

python - 按过滤条件的 Pandas 样本

python - 在 Django Admin 中保存新对象并发送到 Celery 任务后,匹配查询不存在

python - 我想比较叶子持续时间的日期与odoo python中的当前日期

python - 使用python查找图像中黑色/灰色像素的所有坐标

python - 对不适合内存的集合进行 Daskcompute()

python - 使用 Python 将阿拉伯语或任何从右到左的书写系统字符串打印到 Linux 终端

python - 根据重复的列表值减少字典,无论列表的顺序如何

python - 使用 boolean 数组调用 iloc()

python - 根据 Python 的 pandas DataFrame 类,什么是大小可变的?