python从列表中的字符串中删除空格 [英] python removing whitespace from string in a list

查看:1949
本文介绍了python从列表中的字符串中删除空格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个清单清单.我想从中删除前导和尾随空格. strip()方法返回字符串的副本,不包含前导和尾随空格.单独调用该方法不会进行更改.通过此实现,我得到了'array index out of bounds error'.在我看来,列表中的每个列表(0-len(networks)-1)都会有一个"x",而列表中的每个字符串(0-len(networks [x])也将有一个"ay"我和j应该准确地映射到合法的索引,而不是越界吗?

I have a list of lists. I want to remove the leading and trailing spaces from them. The strip() method returns a copy of the string without leading and trailing spaces. Calling that method alone does not make the change. With this implementation, I am getting an 'array index out of bounds error'. It seems to me like there would be "an x" for exactly every list within the list (0-len(networks)-1) and "a y" for every string within those lists (0-len(networks[x]) aka i and j should map exactly to legal, indexes and not go out of bounds?

i = 0
j = 0
for x in networks:
    for y in x:
    networks[i][j] = y.strip()
        j = j + 1
     i = i + 1

推荐答案

遍历第一个列表后,您忘记了将j重置为零.

You're forgetting to reset j to zero after iterating through the first list.

这是您通常不在Python中使用显式迭代的原因之一-让Python为您处理迭代:

Which is one reason why you usually don't use explicit iteration in Python - let Python handle the iterating for you:

>>> networks = [["  kjhk  ", "kjhk  "], ["kjhkj   ", "   jkh"]]
>>> result = [[s.strip() for s in inner] for inner in networks]
>>> result
[['kjhk', 'kjhk'], ['kjhkj', 'jkh']]

这篇关于python从列表中的字符串中删除空格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆