How do you make Python accept multiple strings and break them down in an input?

For example,

main = input ('> ')
if main == ('ECHO',some_words):
    print (some_words)

But everytime I do that, the some_words string wouldn't be defined.
Error Message:

Traceback (most recent call last):
  File "<pyshell#7>", line 1, in <module>
    if main == ('ECHO',some_words):
NameError: name 'some_words' is not defined

Can someone please teach me how?

Recommended Answers

All 6 Replies

Assuming you are using Python 3.x, then the input isn't going to be a tuple of separate strings, but one whole string. This means that you'll need to use .split() on the returned string in order to get the separate tokens.

def shell():
    in_string = input ('> ')
    tokens = in_string.split()
    if tokens[0] == 'ECHO':
        [print(x, end=' ') for x in tokens[1:]]

Mind you, this will only work if the enter value is exactly 'ECHO', all caps. THis probably isn't what you wanted, but I'll leave it to you to make any corrections of that sort.

Mind you, this will only work if the enter value is exactly 'ECHO', all caps. THis probably isn't what you wanted, but I'll leave it to you to make any corrections of that sort.

Thanks, but it always seems to return something like this:

> ECHO haha
haha >

I want it to be like this:

> ECHO Haha
Haha
> 

What do I do to make it happen?

To simulate a command line interpreter, play with the cmd module

from cmd import Cmd

class Interpreter(Cmd):
    def emptyline(self):
        pass

    def do_ECHO(self, line):
        print(line)

    def do_QUIT(self, line):
        return True

interp = Interpreter()
interp.prompt = "> "
interp.cmdloop("\nWELCOME\n")

""" my output --> 

WELCOME

> ECHO hello world
hello world
> 
> ECHO well it's working ...
well it's working ...
> QUIT
"""

@Gribouillis: How do I add a third str into the input?

For example

def do_ADD(self, line, third_str):

@Gribouillis: How do I add a third str into the input?

I don't understand, if you write def do_ADD(self, line), the line variable contains evreything in the input line after the ADD, for example if you type

> ADD foo bar baz

then the value of line in do_ADD() will be the string 'foo bar baz'. You don't need another argument. On the the other hand, you may want to split the line.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.