2

The following code is supposed to double each letter in a particular string (ex. 'hello' to 'hheelllloo') but the function is returning the "list index out of range" error to all string inputs. The problem is obviously caused by a conflict between the ever increasing length of the string with each subsequent insert and the constant value of the length of the array calculated only at the beginning of the for statement.

def double_char(str):
    l = list(str)
    for i in range (0,len(l)+1):
        l.insert(2*i, l[2*i])
    return l

I wanted to figure out if there is some way to continuously calculate the length of the list with each for statement so the insert command will function properly while still keeping the initial range of i fixed.

2
  • Use a while loop instead, manually increment i and compare to len(l). Or use regex: re.sub("(.)", "\\1\\1", str) Commented Aug 4, 2015 at 1:44
  • You shouldn't be using str as a variable name. str is a python built in method. Commented Aug 4, 2015 at 1:49

3 Answers 3

3

Why cannot you use simple str.join() for this? Example -

>>> def double_char(s):
...     return ''.join(c+c for c in s)
...
>>> double_char('hello')
'hheelllloo'
>>> double_char('hellobye')
'hheelllloobbyyee'
Sign up to request clarification or add additional context in comments.

Comments

1

You could just use an empty String, and append to it:

>>>def double_char(word):
...    l = ""
...    for i in word:
...        l += i*2
...    return l

>>> double_char("hello")
'hheelllloo'

Comments

0

Anand's answer is likely the most pythonic. If you are newer to python, readability may be important as well. This would work too:

def doubleString(word):
    newWord = ""
    for letter in word:
        newWord += (2 * letter)
    return newWord

Comments

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.