yuwe
yuwe

Reputation: 159

String out of range [Python]

I'm trying to make a program that combines two words together in python. For example, if I am combining "hello" and "chadd" it will return "hcehlaldod" by alternating letters.

Heres my code:

string1 = "hey"
string2 = "hii"
len1 = len(str(string1))
len2 = len(str(string2))
x = 0
final = ""

while (x <= len1):
  final = final + string1[x] + string2[x]
  x = x + 1

any help?

Upvotes: 1

Views: 122

Answers (4)

Muzol
Muzol

Reputation: 301

There is a simplest way of to do that like this:

string1 = "hey"
string2 = "hii"
new_str = ""

for char1,char2 in zip(string1, string2):
    new_str += char1 + char2


if __name__ == '__main__':
    print(new_str)

Upvotes: 1

Ben
Ben

Reputation: 6348

You can pay attention to the lengths, as others have suggested, but you can also take a more functional approach with the built in zip function:

string1 = "hello"
string2 = "chadd"

string3 = ''.join(t[0] + t[1] for t in zip(string1, string2))  # hcehlaldod

zip works by pairing it's inputs:

print(list(zip(string1, string2)))  # note that you should turn it into a list to print it
# [('h', 'c'), ('e', 'h'), ('l', 'a'), ('l', 'd'), ('o', 'd')]

And you can then just combine those into a string (like my first code snippit does).

Upvotes: 0

AJC24
AJC24

Reputation: 3336

Your immediate problem with your loop is because you're using the condition while (x <= len1):

Let me explain. The length of your string is 3. The characters (and their indexes) are as follows:

0 1 2
h e y

You will see your string ends at index position 2. So now go back to your condition. You have set it to continue looping while (x <= len1):. So your loop will operate when x=0, x=1, x=2 and x=3. The x=3 is out of bounds since the indexes for your string end at index position 2.

What you should use is while (x < len1): which will stop at the correct point in your string.

Upvotes: 0

Andres Salgado
Andres Salgado

Reputation: 243

Change while (x <= len1) to while (x < len1) if you only care about the length of the first string.

If you care about the length of both strings, do while (x < len1 and x < len2) instead.

Upvotes: 0

Related Questions