1

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?

1
  • A better example might be to replace the end=i with end="_" so you can visualize what it is doing. Commented Oct 18, 2019 at 20:15

3 Answers 3

4

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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='')

Comments

1

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.