【问题标题】:How to convert input lists to string in python如何在python中将输入列表转换为字符串
【发布时间】:2021-05-03 01:11:22
【问题描述】:

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 输出并将输入列表转换为字符串?

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

【问题讨论】:

  • L = input("Enter your lst: ")L已经是一个字符串
  • @python_user 当然是的
  • 只输入不带括号的数字。逗号和空格以获得所需的输出
  • 问问自己(并阅读官方文档!),input 语句返回什么?提示:docs.python.org/3/library/functions.html#input
  • @IronFist 我只想知道为什么会这样!

标签: python string list converters


【解决方案1】:

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

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

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

print(result)

【讨论】:

  • 好。谢啦兄弟 。现在只有一件事,我得到的结果是 = [1 2 3],我也可以删除“[]”这个东西吗?
  • 您可以使用strip() 可靠地修剪它以删除任何尾随空格,然后切片:inputdata = input("Enter your lst: ").strip()[1:-1]
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-06-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-02-10
  • 1970-01-01
相关资源
最近更新 更多