1

I am trying to recognise user typed strings such as "exit" or "add number" using this:

 command, data = input('>').split(" ", 1)

It works for two word input, but not one word of input ("need more than 1 value to unpack").

What is the best way of accepting both one/two word inputs?

5 Answers 5

3

This is what partition is for:

command, _, data = raw_input('>').partition(" ")

If only one word was specified, data will be assigned an empty string.

Sign up to request clarification or add additional context in comments.

Comments

2

The best way is to build a parser, but if you just want something to work quickly you could just have a list of the commands you want to allow, such as:

commands = ['foo', 'bar', 'exit', 'hello world', 'add number']

Then for each command check if your input satisfies s.startswith(command). If so, you can do the appropriate thing for that command.

Comments

2

I am certain that someone is going to come up with a "Pythonic" solution, but what ever happened to just accepting it as a list and checking it afterward?

command_data = raw_input('>').split(" ", 1)
if len(command_data) > 1:
  do some brilliant stuff next

Sorry, I think the C++ side of my brain is getting moody :)

Edit: Maybe str.partition is what you're looking for. At least you're guaranteed a 3-tuple to unpack. Mind you if you ever add a second argument to the command you'll have to find a new solution.

Comments

1
line = raw_input('>').split(" ", 1)
command = line[0]
data = line[1] if len(line) > 1 else ""

Make sure you use raw_input if you don't want your data being evaluated as a Python expression.

Comments

1
command, data = (input('>') + ' ').split(" ", 1)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.