Python Forum

Full Version: Move a character left or right in a file.
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Depending on an input ('a' or 'd') I would like to move a character left or right. I already have this:
pos = line.index('4')
pos = pos - 1
new = new + '1'
for i in range(0, pos-1):
    new = new + '0'
new = new + '4'
for j in range(0, pos+1):
    new = new + '0'
new = new + '1'
FYI: Line is '100000040000001'

When I run this code, new becomes: '1000004000001'. This is not the right length. It you use
len()
it returns '13' not '15' like the original. So it should be: '100000400000001' which is still 15 in length.

Hope it makes sense,
Dream.

EDIT: removed dupe post lines
Sorry, deleted the other post.

You're not taking into account the length of the string. That is, pos only tells you how wide the left side should be, and you are setting both the left and the right side based on that. So the further left you move, the shorter the string gets, and the further right you move the longer the string gets.

I would fill in the right side by adding 0's until len(new) == len(line) - 1, and then adding a 1.
(Mar-21-2019, 06:21 PM)ichabod801 Wrote: [ -> ]Sorry, deleted the other post.

You're not taking into account the length of the string. That is, pos only tells you how wide the left side should be, and you are setting both the left and the right side based on that. So the further left you move, the shorter the string gets, and the further right you move the longer the string gets.

I would fill in the right side by adding 0's until len(new) == len(line) - 1, and then adding a 1.

Dont worry!

Thanks for the reply, I can't try it out now, but I can soon. Thinking about it, it should work.

Dream
You can just swap the two values instead of iterating over the string.

    line='100000040000001'
    pos = line.index('4')

    ## move to the left
    line_as_list=list(line)
    if pos > 0:
        new_pos=pos - 1  ## move to right= pos + 1
        save_this=line_as_list[new_pos]
        line_as_list[new_pos]='4'
        line_as_list[pos]=save_this

    ## print one above the other for easy comparison
    print(line)
    print("".join(line_as_list)) 
It works, thanks!