0

So lets say I have a string come in like this:

newData = "[Fruit]Apple"

How would I set set these variables from the string that was sent in?

type = "Fruit"
food = "Apple"
Noivern Evo
  • 111
  • 3
  • 11

2 Answers2

2

replace and split:

type, food = newData.replace('[','').split(']')

Or without replace (credit @Bakuriu), with slicing:

type, food = newData[1:].split(']')
Moses Koledoye
  • 77,341
  • 8
  • 133
  • 139
  • I don't really see the value of using `replace` here. The format is so fixed that it's probably better to just do `newData[1:].split(']')`. If the format gets more complicated the `replace` wouldn't work anyway. – Bakuriu Jul 06 '16 at 14:28
  • @Bakuriu I thought of that too, but I can't be sure of how `[1:]` plays out in a general case either, say when `[` is not at the start of the string. – Moses Koledoye Jul 06 '16 at 14:52
  • If `[` is not at the start your solution fails too, because you obtain `type = " Fruit"` (with initial space) instead of `"Fruit"` which may be significant if that string is used to lookup something etc. – Bakuriu Jul 06 '16 at 15:58
  • @Bakuriu `replace` would not leave a leading space if `[` is not at the start – Moses Koledoye Jul 06 '16 at 16:00
  • Yes it does: the leading space before the `[` ends up into the `type`: `>>> ' [a]b'.replace('[', '').split(']') -->[' a', 'b']`. Sure, you could `lstrip` the data before but at that point again you could just do `newData.lstrip()[1:]`. – Bakuriu Jul 06 '16 at 16:07
  • @Bakuriu Seems there's a misunderstanding. OP's question has no leading space. – Moses Koledoye Jul 06 '16 at 16:08
  • *You* were the one that bring to my attention the possibility of `[` not being at the start. My whole point is: if the format is there is always a single `[` at the start of the string, then `[1:]` is just simpler and better. If `[` might not be at the start your solution wont work correctly anyway without some adjustment. So, either you go on and generalize it a bit moreto handled such cases, or you are just suggesting a complicated way of doing `[1:]`. I hope to have been clear now. – Bakuriu Jul 06 '16 at 16:23
  • @Bakuriu Ah that! I get the point the point now. I will add the `[1:]` version. – Moses Koledoye Jul 06 '16 at 16:39
0

You can use .split()

food = newData.split(']')[-1]
type = newData.split(']')[0].split('[')[-1]
jmatthieu
  • 93
  • 1
  • 7