Title: String out of range [Python]
Tags: python-3.x
Question: 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))
final = ""
while (x <= len1):
final = final + string1[x] + string2[x]
x = x + 1
any help?
Comment: You are iterating out of bounds. Python string is starting indexing from `0` to `len(string)-1`.


Here is another answer: 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)

Here is another answer: 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).

Here is another answer: 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.

Here is another answer: 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:
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.

{'source': 'StackExchangeDataset', 'subset': 'stackoverflow.com', 'metadata': {'AnswerCount': 4, 'CommentCount': 1, 'ContentLicense': 'CC BY-SA 4.0', 'CreationDate': '2018:00:07/12/18', 'FavoriteCount': None, 'PostTypeId': 1, 'Tags': '<python-3.x>', 'Title': 'String out of range [Python]', 'ViewCount': 90, 'id': 51313271, 'user_AboutMe': '<p>I like to code for fun.</p>\n', 'user_AccountId': 13948401.0, 'user_DisplayName': 'yuwe', 'user_Reputation': 157.0, 'user_Views': 36.0, 'user_id': 10072577.0}}