首页 > 解决方案 > Python how do it get pure data from user input in an entry widget=

问题描述

I want to get the raw data from user input but i get it a string.

My goal is to get this:

X =[[8,5,3,9,1,4]]

Now i want the user to put in (Entry widget) 8,5,3,9,1,4

So i saved it in a variable like :

Y= entry.get()
X = [[Y]]

Now Y is from data type String so what i get is:

X=[["8,5,3..."]]

But I want the 'pure' data like 8,5,7... not a string '8,5,7'. What can I do?

标签: pythonstring

解决方案


“我想从用户输入中获取原始数据,但我得到了一个字符串。”

嗯,这实际上“原始数据”。

我得到的是X=[["8,5,3..."]]但我想要像 8,5,7 这样的“纯”数据。

所以你的问题是“我如何将逗号分隔的数字字符列表解析为整数列表”。这实际上很简单:用逗号分割字符串,将每个部分传递给int,然后收集结果:

X = [[int(part.strip()) for part in Y.strip().split(",")]]

请注意,如果用户不遵循预期的输入格式,这将中断 - 但这不是问题的一部分(提示:您可以使用正则表达式预先验证输入格式,或捕获异常)。


推荐阅读