首页 > 解决方案 > 如何在python中将输入列表转换为字符串

问题描述


L = [1,2,3]       

q = " ".join(str(x) for x in L)

print(q)

# as you see input is = L = [1,2,3]

# when you run the code output = 1 2 3

但是当我想像这样使用这段代码时:


L = input("Enter your lst: ")
     
q = " ".join(str(x) for x in L)

print(q)

# I enter my input again = [1,2,3]

# and the output is = [ 1 , 2 , 3 ]

# but I was looking for this : 1 2 3

这里有什么问题?我应该怎么做才能获得 True 输出并将输入列表转换为字符串?

我对编码很熟悉,所以简单的解释会更好。

标签: pythonstringlistconverters

解决方案


input()在 python 中返回一个字符串。您需要将结果转换input()为 alist然后将其传入。

如果用户将列表输入为逗号分隔值(例如“1,2,3”),那么我们可以像这样解析数据:

inputdata = input("Enter your lst: ")
valueList = [v.strip() for v in inputdata.split(",")]
     
result = " ".join(valueList)

print(result)

推荐阅读