0

I have read all the python docs on String.replace, yet I am still having trouble with my code. My code is as follows:

#within a class
def fixdata(self):
    global inputs_list
    for i in range(0, len(inputs_list)):
        inputs_list[i].replace("\n", "")
        print(inputs_list[i]) # to check output

What I am hoping for is that all \n characters (newlines) are replaced with empty string ""so that trailing newlines are removed. .strip(), .rstrip(), and, I'm assuming, .lstrip() do not work.

Seanny123
  • 8,776
  • 13
  • 68
  • 124
  • Strings in python are immutable. You need to assign the result of `string.replace()` to something. – jordanm Jan 06 '19 at 00:32

2 Answers2

1

Dok: string.replace()

Return a copy of string s with all occurrences of substring old replaced by new. If the optional argument maxreplace is given, the first maxreplace occurrences are replaced.

You replace and throw the copy away:

#within a class
def fixdata(self):
    global inputs_list
    for i in range(0, len(inputs_list)):
        inputs_list[i].replace("\n", "")           # Thrown away
        print(inputs_list[i]) # to check output

More doku:

Fix:

def fixdata(self):
    global inputs_list   # a global in a class-method? pass it to the class and use a member?
    inputs_list = [item.rstrip() for item in input_lists]
Patrick Artner
  • 50,409
  • 9
  • 43
  • 69
0

You need to assign the new string like this:

inputs_list[i] = inputs_list[i].replace("\n", "")
Dan
  • 527
  • 4
  • 16