Tejasisamazing
Tejasisamazing

Reputation: 39

Splitting string on the first occurance of any one of multiple delimiters

Lets say i have a string

a = "Apple;Bananas-Mangoes/Strawberries"

Now what i want to do is split the string on the first occurance of either of these characters(; or - or /).

like b = ["Apple","Bananas-Mangoes/Strawberries"]

But if used a different character at the start instead of the ; , i want to split from that instead.

a = "Apple/Bananas-Mangoes;Strawberries"

b = ["Apple","Bananas-Mangoes;Strawberries"]

So any way to achieve this in Python?

Upvotes: 2

Views: 75

Answers (3)

Dariva
Dariva

Reputation: 370

You could do the following

import re

s1='Apple;Bananas-Mangoes/Strawberries'
s2='Apple/Bananas-Mangoes;Strawberries'

p ='(;|\\/|-)'

s=s1
m=re.search(p,s)
print([s[0:m.regs[0][0]],s[m.regs[0][0]+1:-1]])

s=s2
m=re.search(p,s)
print([s[0:m.regs[0][0]],s[m.regs[0][0]+1:-1]])

Upvotes: 0

Ajax1234
Ajax1234

Reputation: 71471

You can use re.split:

import re
a = "Apple;Bananas-Mangoes/Strawberries"
result = re.split('[;/\-]', a, 1)

Output:

['Apple', 'Bananas-Mangoes/Strawberries']

Upvotes: 2

user15801675
user15801675

Reputation:

You can use any() which returns True if the condition is met:

a = "Apple/Bananas-Mangoes;Strawberries"
not_l=['-','/',';']
for i in a:
    if any(i==k for k in not_l):
        c=a.split(i)
        print(c)
        break

Upvotes: 0

Related Questions