简体   繁体   English

从 Python 字符串中删除前导 + 尾随空格和换行符,.strip() 不起作用?

[英]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.我目前正在上我的第二门 Python 课程,在我们的复习预热中,我被一个看似简单的问题难住了。 Here's how it's stated:这是它的表述方式:

In this exercise, your function will receive 1 parameter, the name of a text file.在本练习中,您的函数将接收 1 个参数,即文本文件的名称。 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.如果该行少于 5 个字符,则应跳过该行。 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. CodeGrinder 然后根据随机生成的 .txt 文件对其进行评分。 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 AssertionError: False is not true : Fifthchar(rprlrhya.txt) 返回 mylgcwdnbi

dmou.德穆。 It should have returned mylgcwdnbidmou.它应该返回 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.似乎换行符正在通过我的.strip()潜入,我不知道如何删除它们。 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.我认为.strip()会删除\\n ,并且我已经尝试了从.rstrip()fifthstring.join(fifthstring.split())所有内容,以在循环中去除第五字符串和 x 的冗余。 How are these newlines getting through?这些换行符是如何通过的?

Your solution is not taking in consideration several things:您的解决方案没有考虑以下几点:

  1. empty lines where its fifth char is the '\\n' char.空行,其中第五个字符是 '\\n' 字符。
  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. strip() 不会改变 x,您需要重新分配剥离的字符串。

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)

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() )

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM