How to remove substring from string in Python 3

后端 未结 2 1258
清酒与你
清酒与你 2021-01-28 14:41

I am new to Python 3. Currently, I am working on a project that requires ne to go through a csv file (without using the csv modules) and extract numbers. While I have been able

相关标签:
2条回答
  • 2021-01-28 14:51

    Current code issues

    replace doesn't work in-place. Instead it returns a string with the replacement done. Hence, for fix #1 you should change your statement from:

    row[i].replace("\\n", " ")
    

    to:

    row[i] = row[i].replace("\\n", " ")
    

    However, the bigger problem is the iteration over the list obtained from the .split(",") operation.

    In fact, your iteration runs short of 1 element, hence never touches the last item, and thus never removes the \n. Let's do some math:

    row = ['13.9', ' 5.2', ' 3.4\n']
    # len(row)  == 3
    # len(row) - 1 == 2
    # range(len(row) - 1) == [0 1], which will do 2 iterations instead of 3
    

    So, fix #2 would be to correct that for loop, which should look something like:

    for row in open(filename):
        row = row.split(",")
        for i in range(len(row)):  # notice the absence of -1
            row[i] = row[i].replace("\n", "")
            row[i] = float(row[i])
        lines.append(row)
    

    Better way

    Since every line of a CSV file has an ending \n, you might as well strip it before you split the columns and perform the conversion str to float via map, like this:

    lines = []
    for row in open(filename):
        row = row.strip().split(",")  # first remove the "\n" then split
        row = list(map(float, row))   # [13.9, 5.2, 3.4]
        lines.append(row)
    
    0 讨论(0)
  • 2021-01-28 14:54

    Strings are immutable in Python, so you will need to always assign row[i] back to the modified version of itself:

    for row in open(filename):
        row = row.split(",")
        for i in range(len(row) - 1):
            row[i] = row[i].replace("\n", "")  # CHANGE HERE
            row[i] = float(row[i])
        lines.append(row)
    

    Note: You don't need to double escape the backslash in \n when using regular string replace.

    0 讨论(0)
提交回复
热议问题