简体   繁体   中英

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!'

Strings are immutable and they don't have any remove or insert method. So, you should convert your string to a list first and then you can use list.remove and list.insert .

>>> x = "th i s. i s. a. n i c ^ e . s t r i ng."
>>> list(x)
['t', 'h', ' ', 'i', ' ', 's', '.', ' ', 'i', ' ', 's', '.', ' ', 'a', '.', ' ', 'n', ' ', 'i', ' ', 'c', ' ', '^', ' ', 'e', ' ', '.', ' ', 's', ' ', 't', ' ', 'r', ' ', 'i', ' ', 'n', 'g', '.']

And finally after modifying the list you can join it back using str.join .

Errors in your code:

 x.remove('^')     # you should remove '^' here, not the index
 x.insert(j, '^')  # first argument is the index, second is the item

[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 sa nic^ e. ss t. stri ng.

I'm not sure I completely understand the issue but here are a couple of examples on how you can move a character within a sequence of characters.

Moving Character To Index

def move_char_index(chars, char, new_index):
    # Convert character sequence to list type.
    char_list = list(chars)
    # Get the current index of the target character.
    old_index = char_list.index(char)
    # Remove the target character from the character list.
    char = char_list.pop(old_index)
    # Insert target character at a new location.
    char_list.insert(new_index, char)
    # Convert character list back to str type and return.
    return ''.join(char_list)

Examples:

chars = 'th i s. i s. a. n i c  ^e . s t r i ng.'
char = '^'

# Move character to the end of the string.
print move_char_index(chars, char, len(chars)) 
# Result: th i s. i s. a. n i c  e . s t r i ng.^

# Move character to the start of the string.
print move_char_index(chars, char, 0) 
# Result:  ^th i s. i s. a. n i c  e . s t r i ng.

Moving Character By Increment

def move_char_by_increment(chars, char, increment):
    # Convert character sequence to list type.
    char_list = list(chars)
    # Get the current index of the target character.
    old_index = char_list.index(char)
    # Remove the target character from the character list.
    char = char_list.pop(old_index)
    # Insert target character at a new location.
    new_index = old_index + increment
    char_list.insert(new_index, char)
    # Convert character list back to str type and return.
    return ''.join(char_list)

Examples:

chars = 'th i s. i s. a. n i c  ^e . s t r i ng.'
char = '^'

# Move character forward by 1.
print move_char_by_increment(chars, char, 1) 
# Result: th i s. i s. a. n i c  e^ . s t r i ng.

# Move character backward by 1.
print move_char_by_increment(chars, char, -1) 
# Result: th i s. i s. a. n i c ^ e . s t r i ng.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM