Reputation: 311
I've just discovered that in my course, the lecturer doesn't want us to use the 'import' function, as it's apparently 'too advanced for the student's needs at this point.'
Messing around with what I am "allowed" to use, I've come up with this:
#!/usr/bin/python
moo = raw_input ('moo ')
string = ''.join(moo)
outp = string.split()
for word in outp:
print word
which gives me
$ ./pecho
moo hello world
hello
world
How to I fiddle with what I've got here to put the "hello world" output on one line?
Original post:
I need to create a python file that "simply prints its own arguments, each separated by one space." For example, the following command will give the output shown:
$ pecho first and then another one
first and then another one
$
IS THIS simply something like
#!/usr/bin/python
moo = raw_input ('moo ')
print moo
? If so, how do I make it so that it prints exactly only one space between the words in the output, regardless of how many tabs/spaces there are in the input?
Upvotes: 0
Views: 178
Reputation: 11935
Here's the answer to the revised question:
moo = raw_input ('moo ')
print ' '.join(moo.split())
Starting from the inside of the parens, we first take the input moo
and split it up into pieces based on the whitespace. That gives us an iterable list, similar to sys.argv
in the old answer.
Then, I join that list using join, and a single space. Then print the whole deal.
To understand this better, here is the same thing, but using more lines:
moo = raw_input('moo ')
temp_list = moo.split()
print ' '.join(temp_list)
Try printing the temp_list too, to see what it looks like.
Just add this as the last line, to see how a list is printed:
print temp_list
You probably want this:
import sys
if len(sys.argv) > 1:
for arg in sys.argv[1:]:
print arg,
sys.argv is a list of the command line arguments. The first one is the name of your script.
A list is an iterable type, so you can use the for loop to iterate on it. I split the list such that I start with the second item in it.
I use a comma at the end of the print line to tell python not to print a newline. There's a different method for doing that in python 3.
In python 3 the last line would be:
print(arg, end=" ")
To use Dan D's example you would just do:
import sys
if len(sys.argv) > 1:
print ' '.join(sys.argv[1:])
You could still test to make sure you have at least one more arg than your script name. It joins together the iterable list with a space in between each item.
Upvotes: 3