#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jul 2013
    Posts
    2
    Rep Power
    0

    SOLVED: Error in .replace() function?


    The code for my program is:

    Code:
    linesheet = open("textfile.txt", mode ='r')
    (more code...)

    Code:
    for entry in linesheet:
        if '\n' in entry:
            entry.replace('\n', '')
    (more code...)

    "textfile.txt" is a text file that consists of lines like:
    470
    225
    326
    etc.
    So, to convert to integers, I remove the '\n', and use int()
    Then, its says:
    Code:
    Traceback (most recent call last):
      File "C:/Python33/python_file.py", line 10, in <module>
        numberlist.append(int(entry))
    ValueError: invalid literal for int() with base 10: '470\n'
    To try debugging, I printed the "entry" before the .replace()

    Code:
    470
    Then after:

    Code:
    470
    It still has a newline!

    The "if" block works, because that's where I added the print() to test.

    I also:

    - copied "linesheet" on to a list, in case the mode='r' didn't let me edit entry (which never happened before)

    - printed all values everywhere (.replace never changed them!)

    - copy pasted code into shell (it didn't work)

    - tested all the functions I used (they worked just fine, including .replace)

    - explicitly converted variables to str or int depending on what was needed.

    The only problem I see is one line:

    Code:
    entry.replace('\n', '')
    Which works in shell (without the linesheet/entry stuff)
    but not in the program.

    There is probably something wrong with the entry/linesheet then, but I copied linesheets items into a list, which I printed, and it looked fine. I then used that list in the program, and the first thing after that line of code is the replace block shown above, and it doesn't work.

    Can someone help?
    Last edited by python12345; July 20th, 2013 at 10:10 PM. Reason: Solved
  2. #2
  3. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Dec 2012
    Posts
    114
    Rep Power
    3
    Strings are immutable. The replace() method does not modify the string, it creates a copy of it with the replacements happening. As such, you need to do this instead:
    Code:
    entry = entry.replace("\n", "")
  4. #3
  5. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jul 2013
    Posts
    2
    Rep Power
    0
    It works now!
    Thanks for the help
  6. #4
  7. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Oct 2012
    Posts
    194
    Rep Power
    2
    In this case best practice would probably be to use strip rather than replace.

    Code:
    for entry in linesheet:
        entry = entry.strip()
    -Mek

IMN logo majestic logo threadwatch logo seochat tools logo