1

I am writing a simple code. I am trying to duplicate every letter in a string. For example if we use my current username here on stackoverflow Jos I want to run a loop and fill an empty string with a duplicate of every letter. so I want it to be JJooss However whenever I run the loop, it does not fill it all and only gives me the last index element in the string. It just gives ss Here is my code:

char="Jos"
list_char=list(char)
new_char=""
for i in range(len(list_char)):
    new_char=list_char[i]*2

print(new_char)

I was wondering what I could be possibly doing wrong in the loop?

dejanualex
  • 3,872
  • 6
  • 22
  • 37
Jos
  • 127
  • 6

1 Answers1

2

Using string concatenation

Use the code:

char="Jos"
list_char=list(char)
new_char = ''
for i in range(len(list_char)):
    new_char = new_char+(list_char[i]*2)

print(new_char)

Output:

JJooss
Subbu VidyaSekar
  • 2,503
  • 3
  • 21
  • 39
  • 1
    Why not `new_char += list_char[i] * 2`? – costaparas Jan 28 '21 at 12:28
  • 3
    Most of this code (except one line) is similar to the original. It would be much more helpful if you posted that single line or explained the change instead of having readers play "find the differences" – Tomerikoo Jan 28 '21 at 12:28
  • Thank you, I understand now. – Jos Jan 28 '21 at 12:29
  • 2
    Btw `for i in range(len(...))` is an [anti-pattern](https://stackoverflow.com/questions/53358753/why-we-use-rangelen-in-for-loop-in-python). In many cases, including this one, `for element in list` would be suitable and cleaner. – costaparas Jan 28 '21 at 12:31