Search code examples
pythonstringpositioncharactermove

python move characters based on string position


I am trying to move a special character from one position to another in a string. I want it to appear after the next character. Here is my string:

"th i s. i s. a. n i c ^ e . s t r i ng."

This symbol can appear at any point. I have been able to identify the next space but I still can't move it.

What I have done so far is this:

x= "th i s. i s. a. n i c ^ e . s t r i ng."
for i in range(len(x)):
    if x[i] == '^':
        j = i + 1
        if x[j] == ' ':
            j = j + 1
            while j < len(x) and x[j] != ' ':
                j = j + 1

            print "in the position " + str(i) + ", I found a hat: '" + str(x[i]) + "'"
            print "in the position " + str(j) + ", I found the next space: '" + str(x[j]) + "'"
            x.remove(i)
            x.insert('^', j)
        else:
            print 'somebody help!'

Solution

  • [Update]

    Thank you for all the great responses. I found a solution to my own question after messing with it for a while. I hope this helps someone else! :-)

    x= "th i s. i s. a. n i^ c e. s s t. s t r i ng."
    for i in range(len(x)):
        if x[i] == '^':
            j = i + 1
            if x[j] == ' ':
                j = j + 1
                while j < len(x) and x[j] != ' ':
                    j = j + 1
                    print x
                x= x[0:i] + x[i+1:]
                x= x[0:j-1] + "^" + x[j-1:]
                print x
                exit()
    

    result: th i s. i s. a. n i c^ e. s s t. s t r i ng.