Dariiu
Dariiu

Reputation: 35

Python: Only using "maxsplit" in one of them, I need to split a string multiple times

I started studying Python yesterday and I wanted to study a little about the string split method.

I wasn't looking for anything specific, I was just trying to learn it. I saw that it's possible to split multiple characters of a string, but what if I want to use the maxsplit parameter in only one of those characters?

I searched a little about it and found nothing, so I'm here to ask how. Here's an example:

Let's suppose I have this string:

normal_string = "1d30 drake dreke"

I want this to be a list like this:

['1', '30', 'drake', 'dreke']

Now let's suppose I use a method to split multiple characters, so I split the character 'd' and the character ' '.

The thing is:

I don't want to take the "d" from "drake" and "dreke" off, only from "1d30", but at the same time I don't want this, I want to split all of the space characters.

I need to put a maxsplit parameter ONLY at the character "d", how can I do it?

Upvotes: 1

Views: 409

Answers (1)

Dani Mesejo
Dani Mesejo

Reputation: 61920

Do the following:

normal_string = "1d30 drake dreke"

# first split by d
start, end = normal_string.split("d", maxsplit=1)

# the split by space and concat the results
res = start.split() + end.split()

print(res)

Output

['1', '30', 'drake', 'dreke']

A more general approach, albeit more advanced, is to do:

res = [w for s in normal_string.split("d", maxsplit=1) for w in s.split()]
print(res)

Upvotes: 2

Related Questions