Python Forum
Move a character left or right in a file.
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Move a character left or right in a file.
#4
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)) 
Reply


Messages In This Thread
RE: Move a character left or right in a file. - by woooee - Mar-21-2019, 07:10 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Writing string to file results in one character per line RB76SFJPsJJDu3bMnwYM 4 3,706 Sep-27-2022, 01:38 PM
Last Post: buran
  PyQT5 - align left frohr 7 6,464 May-07-2022, 09:56 PM
Last Post: deanhystad
  How did one column get left-justified? Mark17 6 3,048 Feb-26-2022, 11:55 PM
Last Post: deanhystad
  [solved] unexpected character after line continuation character paul18fr 4 6,715 Jun-22-2021, 03:22 PM
Last Post: deanhystad
  Move file from one folder to another folder with timestamp added end of file shantanu97 0 3,109 Mar-22-2021, 10:59 AM
Last Post: shantanu97
  SyntaxError: unexpected character after line continuation character siteshkumar 2 4,162 Jul-13-2020, 07:05 PM
Last Post: snippsat
  Shutil move if file exists in destination Friend 2 9,534 Feb-02-2020, 01:45 PM
Last Post: Friend
  how can i handle "expected a character " type error , when I input no character vivekagrey 2 3,564 Jan-05-2020, 11:50 AM
Last Post: vivekagrey
  How to left align the columns SriRajesh 6 5,187 Dec-28-2019, 04:04 PM
Last Post: SriRajesh
  Replace changing string including uppercase character with lowercase character silfer 11 8,470 Mar-25-2019, 12:54 PM
Last Post: silfer

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020