从列表中删除字符

3

我尝试了数小时,但仍未找到解决方案(在SE上也是如此)。我的问题如下:通过使用Beautifulsoup解析HTML表格,我创建了一个列表,它给出了以下结果:

results = [[None, ' Windows 64 bit\n\t\t'], ['\n\t   Official\n\t'], ['blender-2.76-3f602ff-win64.zip'], ['108M'], ['\n\t  Thu Feb 25 09:21:53 2016\n\t'], [None, ' Mac OS X 64 bit\n\t   \t\t'], ['\n\t   Official\n\t'], ['blender-2.76-ba98b68-OSX-10.6-x86_64.zip'], ['113M'], ['\n\t  Thu Feb 25 09:57:40 2016\n\t'], [None, ' Windows 32 bit\n    \t'], ['\n\t   Official\n\t'], ['blender-2.76-ba98b68-win32.zip'], ['90M'], ['\n\t  Thu Feb 25 11:33:10 2016\n\t'], [None, ' Linux 32 bit\n\t   \t\t'], ['\n\t   Official\n\t'], ['blender-2.76-3f602ff-linux-glibc211-i686.tar.bz2'], ['106M'], ['\n\t  Thu Feb 25 08:33:43 2016\n\t'], [None, ' Linux 64 bit\n\t   \t\t'], ['\n\t   Official\n\t'], ['blender-2.76-3f602ff-linux-glibc211-x86_64.tar.bz2'], ['108M'], ['\n\t  Thu Feb 25 08:33:24 2016\n\t'], ['\xa0\n'], ['\xa0\n'], ['\xa0\n'], ['\xa0\n'], ['\xa0\n']]

现在我想删除文本中的 \n 和 \t 字符,空格以及结尾处的 \xa0\n。我尝试使用 results = list(map(str.strip, results)) 对列表进行映射,但是没有任何变化,列表保持不变。 我对 Python 不熟悉,即使在这里查看了其他示例,也没有找到适合我的解决方案。 提前感谢您!
1个回答

4

试试这个:

results = [[item.strip().strip("\xa0") if item is not None else None for item in sublist] for sublist in results]

我想要移除掉 \n 和 \t 字符,以及空格... 这样才能使代码正常运行,但是你的 strip 对于 OP 的情况来说太狭窄了。 - Two-Bit Alchemist
你的意思是什么?我使用 .strip() 去除所有空格,然后用 .strip("\xa0") 去除 "\xa0"。还有什么不够? - zondo
抱歉,我读得太快了,我的注意力跳过了重复的strip调用。继续吧 :) - Two-Bit Alchemist
@tobkum:很高兴能帮忙。(尤其是我因此获得了55个声望值 :)) - zondo

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接