BSweat
BSweat

Reputation: 47

Removing leading + trailing whitespace and newlines from a Python string, .strip() not working?

I'm currently in my second Python course and in our review warm-ups I'm getting stumped by a seemingly simple problem. Here's how it's stated:

In this exercise, your function will receive 1 parameter, the name of a text file. The function will return a string created by concatenating the fifth character from each line into one string. If the line has fewer than 5 characters, then the line should be skipped. All lines should have leading and trailing whitespace removed before looking for the fifth character.

CodeGrinder then grades it based off of randomly generated .txt files. Here's the code I currently have:

def fifthchar(filename):
    file = open(filename)
    fifthstring = ''
    for x in file:
        x.strip('\n ')
        if len(x) >= 5:
            fifthstring += x[4]
        else:
            pass
    fifthstring.strip('\n ')
    return fifthstring

And the error in return:

AssertionError: False is not true : fifthchar(rprlrhya.txt) returned mylgcwdnbi

dmou. It should have returned mylgcwdnbidmou. Check your logic and try again.

It seems that newlines are sneaking in through my .strip(), and I'm not sure how to remove them. I thought that .strip() would remove \n, and I've tried everything from .rstrip() to fifthstring.join(fifthstring.split()) to having redundancy in stripping both fifthstring and x in the loop. How are these newlines getting through?

Upvotes: 0

Views: 5117

Answers (2)

lenik
lenik

Reputation: 23528

This should work:

def fifthchar(filename):
    with open(filename) as fin :
        return ''.join( line.strip()[4] if len(line.strip()) > 4 else '' for line in fin.readlines() )

Upvotes: 1

epinadev
epinadev

Reputation: 116

Your solution is not taking in consideration several things:

  1. empty lines where its fifth char is the '\n' char.
  2. every line's leading and trailing spaces should be removed.
  3. strip() doesn't mutate x, you need to re-assign the stripped string.

Here is your solution:

def fifthchar(filename):
    file = open(filename)
    fifthstring = ''
    for x in file:
        x = x.strip()
        if len(x) >= 5:
            fifthstring += x[4]
        else:
            pass
    fifthstring.strip('\n ')
    return fifthstring

Here is another:

def fifth(filename):
    with open(filename) as f:
        string = '' 
        for line in f.readlines():
            l = line.strip()
            string += l[4] if len(l) >= 5 else ''
        return ''.join(string)

The same as before using list comprehension:

def fifth(filename):
    with open(filename) as f:
        string = [line.strip()[4] if len(line.strip()) >= 5 else '' for line in f.readlines()]
        return ''.join(string)

Upvotes: 2

Related Questions