python string split
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?
This is what partition
is for:
command, _, data = raw_input('>').partition(" ")
If only one word was specified, data
will be assigned an empty string.
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.
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.
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.
command, data = (input('>') + ' ').split(" ", 1)
精彩评论