Syl Morrison
Syl Morrison

Reputation: 13

Split string on one use of a word and not the other

fairly novice here, I'm looking for an effective way to use split() to split a string after a certain word. I'm working on a voice controlled filter using the Csound API in python, and say my input command is "Set cutoff to 440", I'd like to split the string after the word "to", basically meaning that I can say the command however I like and it'll still find my frequency I'm looking for, I hope that makes sense. So at the moment, my code for this is

string = "set cutoff to 440"
split = string.split("to")
print(split)

and my output is

['set', 'cu', 'ff', '440']

The problem is the 'to' in 'cutoff', I know I could fix this by just changing cutoff to frequency but it seems like giving in too easily. My suspicion is there's a way to do this with regular expressions, but I could easily be wrong, any advice would be really helpful, and I hope my post adhered to all the guidelines and stuff, am pretty new to Stack Overflow.

Upvotes: -2

Views: 80

Answers (2)

Writimov
Writimov

Reputation: 1

If you want to use regex for other reasons, here is how to do it: you can find all non-whitespace characters:

import re

string = "set cutoff to 440"
split = re.findall(r'\S+',string)
print(split)

returns

['set', 'cutoff', 'to', '440']

from jamylak on this post: Split string based on a regular expression

Upvotes: 0

Ami Hollander
Ami Hollander

Reputation: 2535

Easy way to do so is to split with spaces around the word to

string = "set cutoff to 440"
split = string.split(" to ")
print(split)

returns

['set cutoff', '440']

using regex to do so is much less efficient than simple split the word surrounded by spaces

Upvotes: 3

Related Questions