删除每行末尾的换行符和不需要的字符



我想从列表中删除换行符和新字符这是我的代码:zenlines=zenlines.strip('\n'(但它给了我一个错误:列表对象没有属性"strip">

它给出了一个错误,因为这是一个列表而不是字符串。正如另一个用户使用列表理解所建议的那样,

z1 = [s.strip("n") for s in zenlines]

这从一开始就删除了,现在要删除不需要的空格,请添加另一个语句

z = [s.strip(" ") for s in z1]
return z

如果zenlines是一个列表,

zenlines =["a  ", "b.."] 
z = [s.strip("n") for s in zenlines]

根据您的场景,您必须使用换行符以及tab或空格字符来删除尝试以下场景将解决您的问题。

zlines = [ line.strip('n') for line in zlines ]
zlines = [ line.strip('   ') for line in lines ]
return zlines

在此处添加实现步骤

z1 = [s.strip("n") for s in zenlines]
z2 = [ line.strip('   ') for line in z1 ]

return z2  # this will pass your test case
#!/bin/python3
import sys
import os
import io

# Complete the function below.
def main():
zenPython = '''
The Zen of Python, by Tim Peters

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!
'''

fp = io.StringIO(zenPython)

zenlines = fp.readlines()

z = [s.strip(" n") for s in zenlines]
return z
'''For testing the code, no input is to be provided'''
if __name__ == "__main__":
f = open(os.environ['OUTPUT_PATH'], 'w')
res = main();
f.write(str(res) + "n")

f.close()

最新更新