Jos
Jos

Reputation: 137

Filling a string from an array with loops only gives me the last element in the index

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?

Upvotes: 1

Views: 243

Answers (1)

Subbu VidyaSekar
Subbu VidyaSekar

Reputation: 2615

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

Upvotes: 2

Related Questions