Search code examples
pythonstringstring-comparison

Error while inserting one string in another


I have a string s= 'aaeekmnnry' and another string p = 'aka'. I want to insert p at the 2nd index at s so that my output is ans = 'aaakaeekmnrry'. To achieve this, I wrote the following piece of code:

f = p[0]
i = 0
while i < len(s):
    if p[0] <= s[i]:
        i+=1
    else:
        break    
ans = ''.join(s[:i]) + ''.join(p) + ''.join(s[i:])

But my index i becomes length of the string and ouput is 'aaeekmnnryaka', I was expecting i to become 2. What am I doing wrong?


Solution

  • You are getting your conditions wrong. You should break out when you see the letter in s is lexicographically higher.

    i = 0
    while i < len(s):
        if p[0] < s[i]:
            break
        else:
            i += 1
    
    ans = s[:i] + p + s[i:]
    # aaakaeekmnnry