2

I'm practicing loops. I've been trying to figure out how to get each character printed 4 times and place aside the others, eg: aaaaccccddddcccc. Right now the returned res is only showing me the last character printed 4 times (cccc). I tried nested for loops but that wasn't working for me either. How do I concatenate the returns? (or is there another way)

def quad_char(letter):
  res = ''
  for i in letter:
    res = i * 4
  return res

print(quad_char('acdc'))
Elohi
  • 35
  • 6

4 Answers4

4

You were almost there! :-)

On every loop, you are re-assigning to res, instead of appending to it (you overwrite res on every iteration, basically).

Try:

def quad_char(letter):
  res = ''
  for i in letter:
    res = res + (i * 4)
  return res

print(quad_char('acdc'))

Which can be shortened to:

def quad_char(letter):
  res = ''
  for i in letter:
    res += i * 4
  return res

print(quad_char('acdc'))

More on string concatenation here.

Also worth looking into the performance of various ways to concatenate strings here.

Community
  • 1
  • 1
Savir
  • 17,568
  • 15
  • 82
  • 136
0

change res = i * 4 to res += i * 4

Jonathan
  • 303
  • 4
  • 14
0

Could also do:

def quad_char(letter):
    for i in letter:
        print ("".join(i*4), end="")
JackTheCrab
  • 132
  • 2
  • 11
0

forget the explicit for loop and use a list comprehension with a join

def quad_char(letters):
    return ''.join(l*4 for l in letters)
tdelaney
  • 73,364
  • 6
  • 83
  • 116
  • this looks interesting but it wasn't working for me. says "letters is undefined" – Elohi Oct 30 '16 at 18:25
  • Your code said `letter` mine says `letters` (I think its less confusing!). If you pasted the function body without changing one of the variable names, you'd get that problem. The solution would be to make sure you use the same name consistently. – tdelaney Oct 30 '16 at 18:39