1

I have a list which contains 3 machines in python which is ARRAY_MACHINE= ['machine1', 'machine2', 'machine3']

And, I want to write a script that can access 2 or 3 items at a same time in that list (depend on the array). If the ARRAY_MACHINE has 3 items like above, it will print out

The machines are machine1, machine2, machine3

If the ARRAY_MACHINE has 2 items, it will print out.

The machines are machine1, machine2

How can I do that? So far, I used while loop to do that, and it can only loop through each item in that list.

0

3 Answers 3

1

print "The machines are" , ', '.join(ARRAY_MACHINE)

This will do the job nicely.

Join function will join the elements of an array with the delimiter specified.

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

Comments

0

Use join:

Python 3:

>>> ARRAY_MACHINE= ['machine1', 'machine2', 'machine3']
>>> print('The machines are {}'.format(', '.join(ARRAY_MACHINE)))
The machines are machine1, machine2, machine3

>>> ARRAY_MACHINE= ['machine1', 'machine2']
>>> print('The machines are {}'.format(', '.join(ARRAY_MACHINE)))
The machines are machine1, machine2

Python 2:

>>> ARRAY_MACHINE= ['machine1', 'machine2', 'machine3']
>>> print 'The machines are {}'.format(', '.join(ARRAY_MACHINE))
The machines are machine1, machine2, machine3

>>> ARRAY_MACHINE= ['machine1', 'machine2']
>>> print 'The machines are {}'.format(', '.join(ARRAY_MACHINE))
The machines are machine1, machine2

3 Comments

Wow, that's awesome. That's print statement suppose to be a command on Linux. And, I was struggle a lot using bash script to do it (since, they are terrible in loop). Thank you a lot :)
@Alexander If you are using python2, print is a statement..in python3 (As i have used) its a function..
I will replace that print statement by a command in Linux. And, I will check the version if Python in my company later
0

Try this

import sys
ARRAY_MACHINE= ['machine1', 'machine2', 'machine3']

for i, data in enumerate(ARRAY_MACHINE):
    if(i == 0 ):
        sys.stdout.write ("The machines are ")
    sys.stdout.write (data+" ")

Comments

Your Answer

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