简体   繁体   English

从字符串和列表中删除python输出中的引号

[英]Removing Quotation marks in python output from string and list

I have to implement a function that takes a parameter of type string and parses this parameter and returns a tuple with the first value of the tuple being the number of units and the second value of the tuple the measurement unit.我必须实现一个函数,它接受一个字符串类型的参数并解析这个参数并返回一个元组,元组的第一个值是单位数,元组的第二个值是测量单位。 I was successful in splitting the number and measurement unit, but I need help with the quotation placement.我成功地拆分了数字和度量单位,但我需要有关报价位置的帮助。

input_value = "3 ft"
split_list = (input_value.split())
print(split_list)
['3', 'ft']

How do I go about getting an output that looks like [3, "ft"] ?我如何获得看起来像[3, "ft"]

input_value = "3 ft"
split_list = (input_value.split())
try:
    split_list[0] = int(split_list[0])
except ValueError:
    split_list[0] = float(split_list[0])
print(split_list) [3, 'ft']

You need to cast the first element of the split_list , ie, the three in your example to an int if you do not want quote marks around the number of units.如果您不想在单位数周围加上引号,则需要将split_list的第一个元素(即示例中的三个元素)转换为int

As for getting double quotes around the measurement unit, by default Python prints strings using single quotes, but you can use json.至于在度量单位周围获取双引号,默认情况下 Python 使用单引号打印字符串,但您可以使用json。 dumps as a workaround since JSON strings have to use double quotes: 转储作为一种解决方法,因为JSON字符串必须使用双引号:

import json

input_value = "3 ft"
split_list = input_value.split()
split_list[0] = int(split_list[0])
print(json.dumps(split_list))

Output:输出:

[3, "ft"]

If you need to support decimals eg, 3.5 ft use float() instead of int() :如果您需要支持小数,例如3.5 ft使用float()而不是int()

import json

input_value = "3.5 ft"
split_list = input_value.split()
split_list[0] = float(split_list[0])
print(json.dumps(split_list))

Output:输出:

[3.5, "ft"]

Try it here .在这里试试。

Suggested建议

What you can do is to convert the value of the list using function .您可以做的是使用function转换列表的值。 So, it will be hackable edited when ever you want to add more formating to it.因此,当您想为其添加更多格式时,它可以被修改

Code代码

List列表

alist = ['3', 'ft']

Function功能

def lista(alist):
    number, measure = alist
    number = int(number)
    alist = [number, measure]
    return alist

Calling Function调用函数

print(alist)
print("print the list after conversion {}".format(lista(alist)))

OUTPUT输出

['3', 'ft']
print the list after conversion [3, 'ft']

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

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