* in print function in python

Question:

text = 'PYTHON'
for index in range(len(text)):
    print(*text[:index + 1])

The * in the print function is producing a space between the characters on sys.stdout. Can someone please tell me what is it called and what does it actually do?

Asked By: Niraj Raut

||

Answers:

It is called an asterisk.

The asterisk passes all of the items in list into the print function call as separate arguments, without us even needing to know how many arguments are in the list.

You can read more about it here:
https://treyhunner.com/2018/10/asterisks-in-python-what-they-are-and-how-to-use-them/

Answered By: James

The print of * for a text is equal as printing print(text[0], text[1], ..., text[n]) and this is printing each part with a space between.
you can do

text = 'PYTHON'
for index in range(len(text))
    print("".join(list(text)[:index + 1]))

or

text = 'PYTHON'
for index in range(len(text))
    print(*text[:index + 1], sep='')

that will print each part without space in between.
Output

P
PY
PYT
PYTH
PYTHO
PYTHON
Answered By: Leo Arad
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.