如何将作为输入的混合数据类型字符串分隔到列表中 [英] how to separate a mixed datatype string taken as input into list
问题描述
考虑以下代码,
string_new=raw_input('Enter data')
提供的输入是:
'aaa''bbb'23 21 56 98'ccc'
'aaa' 'bbb' 23 21 56 98 'ccc'
以上每个值都用空格隔开
Each of the above values were space seperated
我们要求将其转换为列表:
We require this to be converted to list:
list=['aaa','bbb',23,21,56,98,'ccc']
我尝试了前面给出的解决方案 获取列表用户输入的数字
I tried previous solutions as given on Get a list of numbers as input from the user
使用
map(int,string_new.split())
但这仅适用于整数,并且我们有不同的数据类型元素作为输入传递,并用空格分隔.
However that works only for integers and we have different datatypes elements passed as an input and separated by space.
任何建议...
推荐答案
原始输入将用户的输入转换为字符串.下面将产生一个列表,该列表按您的要求在空格上分割.
Raw input converts the input from the user into a string. The following will produce a list that is split on spaces as you are requesting.
string_new = raw_input('Enter data')
input_list = string_new.split()
如果您希望在input_list中转换整数形式:
If you wish to convert integer-likes within the input_list:
mix_list = []
for in_string in input_list:
try:
mix_list.append(int(in_string))
except:
mix_list.append(in_string)
这篇关于如何将作为输入的混合数据类型字符串分隔到列表中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!