繁体   English   中英

Python字符串和数组无法正常工作

[英]Python string and array not working properly

从conditionId输入字段中,我得到逗号分隔的字符串,例如下面的“ Test1”,“ Test2”,“ Test3”是我要拆分该字符串并使用for循环访问单个值的代码

ConditionId =str(request.POST.getlist("ConditionId"))
ConditionIdArray = [n for n in ConditionId[1:-1].split(',')]

for i in range(0,len(ConditionIdArray)):
    print(ConditionIdArray[i])

在打印语句中,它给我输出为

'Test1'
'Test2'
'Test3'

但我想输出为

Test1
Test2
Test3

因为当我将数据存储在数据库中时,它存储为“ Test1”而不是正常的Test1

POST.getlist将返回字符串列表。 不要将其转换为字符串并拆分,只需对其进行迭代即可(无需使用range和索引):

condition_ids = request.POST.getlist("ConditionId")

for condition_id in condition_ids:
    print(condition_id)

@falsetru的答案有一些解释性补充。 liststr()使用repr()来显示其元素,因此对于[x, y, z]为:

[repr(x), repr(y), repr(z)]

而不是人们所期望的

[str(x), str(y), str(z)]

对于字符串,则有所不同:

> s = 'Test1'
> print(str(s))
Test1

> print(repr(s))
'Test1'  # so, splitting the str(list) on commas leaves the quotes

暂无
暂无

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

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