how to separate a mixed datatype string taken as input into list
Asked Answered
A

1

1

Consider the below code,

string_new=raw_input('Enter data')

The input supplied was:

'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

and How to make a list from a raw_input in python?

using

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.

Any suggestions...

Alys answered 6/5, 2017 at 16:37 Comment(1)
our string is carrying mixed datatype Well not really - a string is a string, even if it contains digits.Zach
S
3

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()

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)
Softshoe answered 6/5, 2017 at 16:43 Comment(4)
@FarhanPatel well raw_input gives you a string, and split() will only work on strings.Zach
@patrick, however that's not the output which is desired!!!.... split would result in [' "aaa" ', ' "bbb" ', '23','21'.....Alys
@BryceFrank, hey buddy pls run the edited answer in any of the python ide, u would see the if it's not a integer it results in [' "aaa" ', ' "bbb" '].....where in it becomes string of string.....Alys
also, i hv suggested edit for string_new and string_input variable mismatch!!!...@BryceFrank pls verify!!Alys

© 2022 - 2024 — McMap. All rights reserved.