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

4 Answers 4

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.

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

2 Comments

Thanks to @Bobby for the extra link providing performance comparisons between different ways of concatenating strings :+1:
Awesome, Thanks guys
0

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

Comments

0

Could also do:

def quad_char(letter):
    for i in letter:
        print ("".join(i*4), end="")

Comments

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)

2 Comments

this looks interesting but it wasn't working for me. says "letters is undefined"
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.