unkn0wn.dev
unkn0wn.dev

Reputation: 235

End in for loop Python

I want to print a string with the same character repeated once right after it. For example, if the input is "hello", the program would output "hheelllloo". The code

for i in "hello":
  print(i, end=i)

works, but I suppose I just do not understand it. I would expect this to give the same output as:

for i in "hello":
  print(i + i)

Could anyone explain how the top code works?

Upvotes: 1

Views: 68

Answers (3)

whege
whege

Reputation: 1441

The other answers get to this point kind of circuitously, but the basic idea is that the default value for "end" is a newline, so each time you run through the loop it will print a newline and each successive iteration gets printed on a new line. By changing end to "end=i" or "i+i, end=''", you override this default and print each run of the loop on the same line.

Upvotes: 1

Daniel H
Daniel H

Reputation: 7433

The default value of end is a newline. So the second option is equivalent to:

for i in "hello":
  print(i + i, end='\n')

You could do something like the second one with

for i in "hello":
  print(i + i, end='')

since this explicitly sets end to the empty string so it won't print anything extra.

Upvotes: 4

Ruzihm
Ruzihm

Reputation: 20249

print(x) will append a newline character to the end of the string it prints.

One way to get rid of that is by setting end='' to have it append an empty string (equivalent to not appending anything at all) instead:

for i in "hello":
  print(i + i, end='')

Upvotes: 2

Related Questions