简体   繁体   English

如何从python列表中删除字符

[英]how to remove characters from python list

I have the follow python code which is a list.我有以下 python 代码,它是一个列表。 For some reason I get unwanted characters in the list how can we remove these characters from the beginning and end of list.出于某种原因,我在列表中得到了不需要的字符,我们如何从列表的开头和结尾删除这些字符。

stuff = []
a = ('{"type": "push"}')
stuff.append(a)

print(stuff)

outputs产出

['{"type": "push"}']

How can we remove the [''] and output like我们如何删除['']并像这样输出

{"type": "push"}

By doing the following :通过执行以下操作:

 a = ('{"type": "push"}')

you are appending a string ( type(a) returns str ).您正在附加一个字符串( type(a)返回str )。 What you might want instead is to append a dictionary你可能想要的是附加一个字典

a = {"type": "push"}    # ===> output = [{"type": "push"}]

which will give you the right output这会给你正确的输出

I think you are assuming that a will be a tuple.我认为您假设 a 将是一个元组。 However, that's not the case.然而,事实并非如此。 In your current implementation it will be a string.在您当前的实现中,它将是一个字符串。 That's why when you append(a) the whole string gets appended.这就是为什么当你 append(a) 整个字符串被附加。 Use any other data structures and there is no need of extra quotes that you don't require to be present.使用任何其他数据结构,并且不需要您不需要出现的额外引号。

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

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