显示列表元素就像输入它们一样

时间:2020-05-13 07:38:02

标签: python string python-2.x

这是代码:

const mongoose = require('mongoose')

const Schema = mongoose.Schema()

const productSchema = new Schema(
    {
        name : {
            type: String,
            required : true
        },
        price : {
            type : Number,
            required : true 
        },
        units: {
            type: String,
            enum: ['KG', 'liters', 'meters', 'cm'],
            required : true 
        }
    }
)

它说:

TypeError:序列项目1:预期的str实例,找到的int

是否有一种无需查看元素类型即可加入的方法?

test = ['26', 1, '050120', '084922', u'43034775', u'RRR', '', None]
print(', '.join(test))

不是一个好的解决方案。打印:

', '.join(str(v) for v in test)

我想保留元素类型,并按原样打印:

26, 1, 050120, 084900, 21747, 1200.0, X, X, 18034775, 5TDDK3DC4BS029227, , None

3 个答案:

答案 0 :(得分:1)

您可以使用内置的repr

print(', '.join(map(repr, test)))

这会产生所需的输出,因为

对于许多类型,此函数会尝试返回一个字符串,该字符串在传递给eval()时将产生具有相同值的对象

示例:

>>> str(1)
'1'
>>> str('1')
'1'
>>> repr(1)
'1'
>>> repr('1')
"'1'"

答案 1 :(得分:0)

如果仅用于打印目的:

test = ['26', 1, '050120', '084922', u'43034775', u'RRR', '', None]

print(str(test)[1:-1])

答案 2 :(得分:0)

达到您的预期输出'26', 1, '050120', '084922', u'43034775', u'RRR', '', None。使用列表的格式并删除括号

test = ['26', 1, '050120', '084922', u'43034775', u'RRR', '', None]
print(str(test).strip("[]")) # '26', 1, '050120', '084922', '43034775', 'RRR', '', None
相关问题