* 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?
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/
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
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?
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/
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