1

What is the role of "*" inside of a print function in Python?

print ("Hello World!\n")
print (*"Hello World!\n")

Output of the first print function is

 Hello World!

Output of the second function is

H e l l o   W o r l d ! 

But in python 2.7 it does not work!

mridul
  • 1,986
  • 9
  • 29
  • 50

1 Answers1

7

* unpacks the sequence given, for example:

>>> print(*[1, 2, 3])
1 2 3

Here, it unpacks the list and prints out each individual item.

In your example, as strings are also a sequence, it prints out each letter separated by a space. Think of the string "Hello world!" as ['H', 'e', 'l', etc]

TerryA
  • 58,805
  • 11
  • 114
  • 143