简体   繁体   English

如何从Python中的列表中删除单引号

[英]How to remove the single quotation mark from a list in Python

I am trying to remove the single quotation marks from this list: 我正在尝试从此列表中删除单引号:

list = ['amazed, 10']

and convert it to 并将其转换为

list = ['amazed', 10]

I used list= [x.strip('') for x in list] but it does not work. 我使用list= [x.strip('') for x in list]但是它不起作用。

Is there a workaround? 有解决方法吗?

Thanks in advance! 提前致谢!

You need to split but not strip , as your list contains a single string 'amazed, 10' that expected to be split into 2 items - 'amazed' and 10 : 您需要split而不是strip ,因为您的列表包含单个字符串'amazed, 10' ,该字符串预计将分为2个项目- 'amazed'10

lst = ['amazed, 10']
lst = [int(i) if i.isdigit() else i for i in lst[0].split(', ')]
print(lst)

The output: 输出:

['amazed', 10]

You can try: 你可以试试:

>>> l = ['amazed, 10']
>>> l = l[0].split(", ")
>>> l
['amazed', ' 10']

as it is a single item in the list, u can split the string using split() method. 因为它是列表中的单个项目,所以您可以使用split()方法拆分字符串。

list=list[0].split(', ')

it will give two separate strings. 它将给出两个单独的字符串。

First you need to split your list to two elements. 首先,您需要将列表分为两个元素。 Next, strip white space and than convert the second element (a string of number) to number (Iv'e converted it to integer but you can convert to float or whatever). 接下来,删除空格,然后将第二个元素(数字字符串)转换为数字(将其转换为整数,但可以转换为浮点数或其他任何值)。

ll = ['amazed, 10']
ll = ll[0].split(",")
ll[1] = int(ll[1].strip())

Try: 尝试:

lst = ['amazed, 10']

lst = [int(i) if i.isdigit() else i for i in lst[0].replace(',', '').split()]

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

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