当前位置: 动力学知识库 > 问答 > 编程问答 >

python - Using the .split() function based on conditions?

问题描述:

How would you be able to use the .split() function based on conditions?

Lets say I have the raw data:

Apples,Oranges,Strawberries Green beans,Tomatoes,Broccoli

My intended result is:

['Apples','Oranges','Strawberries','Green beans','Tomatoes','Brocolli']

Would it be able to have it split at commas and if there is a space and a capital letter following it?

网友答案:

The literal interpretation of what you asked for, using re.split:

import re
pat = re.compile(r'\s(?=[A-Z])|,')
pat.split(my_str)

This is more simply done, in your case:

pat = re.compile(r'.(?=[A-Z])')

Basically, split on any character that is followed by a capital letter.

网友答案:

Using regex will make the code simpler than a complicated split statement.

import re
...
re.findall(", [A-Z]",data)

Note you asked for a split for a command, space, capital, but in your example there are no spaces after commas.

分享给朋友:
您可能感兴趣的文章:
随机阅读: