Python:从列表对象中删除空格 [英] Python: Removing spaces from list objects

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

问题描述

我有一个从mysql数据库附加的对象列表,并包含空格.我希望删除下面的空格,但是im使用的代码不起作用?

I have a list of objects appended from a mysql database and contain spaces. I wish to remove the spaces such as below, but the code im using doesnt work?

hello = ['999 ',' 666 ']

k = []

for i in hello:
    str(i).replace(' ','')
    k.append(i)

print k

推荐答案

Python中的字符串是不可变的(这意味着它们的数据无法修改),因此replace方法不会修改字符串-它返回一个新字符串.您可以按以下步骤修改代码:

Strings in Python are immutable (meaning that their data cannot be modified) so the replace method doesn't modify the string - it returns a new string. You could fix your code as follows:

for i in hello:
    j = i.replace(' ','')
    k.append(j)

但是,实现目标的更好方法是使用列表理解.例如,以下代码使用 :

However a better way to achieve your aim is to use a list comprehension. For example the following code removes leading and trailing spaces from every string in the list using strip:

hello = [x.strip(' ') for x in hello]

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

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