本文介绍了在大写字母处拆分字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

什么是 pythonic 在出现之前拆分字符串的方法一组给定的字符?

比如我想拆分'TheLongAndWindingRoad'在任何出现的大写字母(可能除了第一个),并获得['The', 'Long', 'And', 'Winding', 'Road'].

它还应该拆分单个事件,即来自 'ABC' 我想获得['A', 'B', 'C'].

解决方案

很遗憾,不可能在零上拆分-Python 中的宽度匹配.但是你可以使用 re.findall 代替:

>>>进口重新>>>re.findall('[A-Z][^A-Z]*', 'TheLongAndWindingRoad')['漫长而曲折的道路']>>>re.findall('[A-Z][^A-Z]*', 'ABC')['A', 'B', 'C']

What is the pythonic way to split a string before the occurrences of a given set of characters?

For example, I want to split'TheLongAndWindingRoad'at any occurrence of an uppercase letter (possibly except the first), and obtain['The', 'Long', 'And', 'Winding', 'Road'].

Edit: It should also split single occurrences, i.e.from 'ABC' I'd like to obtain['A', 'B', 'C'].

解决方案

Unfortunately it's not possible to split on a zero-width match in Python. But you can use re.findall instead:

>>> import re
>>> re.findall('[A-Z][^A-Z]*', 'TheLongAndWindingRoad')
['The', 'Long', 'And', 'Winding', 'Road']
>>> re.findall('[A-Z][^A-Z]*', 'ABC')
['A', 'B', 'C']

这篇关于在大写字母处拆分字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-05 07:54