2
stack = list()
stack = [[u'hello','world'],[u'blue','sky']]

How to print 'hello world' separately and 'blue sky' separately in python?

1

6 Answers 6

4

Use pprint, this will work for any size and nesting of array.

>>> import pprint
>>> stack = list()
>>> stack = [[u'hello','world'],[u'blue','sky']]
>>> pprint.pprint(stack)
[[u'hello', 'world'], [u'blue', 'sky']]
>>>

Specifically use this

for s in stack:
    print ' '.join(s)
Sign up to request clarification or add additional context in comments.

Comments

2

Try this way:

    print stack[0][0]+' '+stack[0][1]

More: Consider this piece of code this way, I print certain object (OK, it's an unicode object)combined with 3 parts, the first part is the object from a list object,and the list object comes from stack (which is also a list object). It's like this: list(stack)->list(stack[0])->unicode(u'hello') The second part is a string object: ' '(a space) The third part is just like the first part, list(stack)->list(stack[0])->str('world') Put these 3 parts together comes the result you have seen.

I suggest you think about exactly what the types of the THINGS you are using are. Because for everything in python, if you know the type of it, you most likely will know what built-in functions/methods/operators you can use.This could be great!

And one more thing, I print a unicode object together with 2 str objects.

Comments

1
print "\n".join(map(lambda l: " ".join(map(str, l)), stack))

Comments

1

The idea is to convert each list to string by str.join() before printing.

>>> stack = [[u'hello', 'world'], [u'blue','sky']]
>>> print '\n'.join( ' '.join(s) for s in stack )
hello world
blue sky

Using loops:

>>> stack = [[u'hello', 'world'], [u'blue','sky']]
>>> for s in stack:
...    print ' '.join(s)
...
hello world
blue sky

If you want to modify the list:

>>> stack = [[u'hello', 'world'], [u'blue','sky']]
>>> stack = [ ' '.join(s) for s in stack ]
>>> print '\n'.join( s for s in stack )
hello world
blue sky

Comments

0

I too wanted my answer to be shared with for loop and if condition

if len(stackf) > 0:
        for i in range(len(stackf)):
            print stackf[i][0]
            print stackf[i][1]

Comments

0

Another option with f-strings:

stack = [[u'hello','world'],[u'blue','sky']]
print('\n'.join([f"{d} {e}" for (d,e) in stack]))

Output:

hello world
blue sky

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.