Home > database >  Separating element type with list from input
Separating element type with list from input

Time:08-30

Trying to separate int, string, float from the list and put them in their variable. It's easy to do with predefined list. I am trying to do with input list.

NumList  = input("Enter string, int, float with the list : ")
#NumList = [1, 4.9, 4, "Five", 6, 7, "Eight", "#" ,2, 15, "$", "."]
StrList = []
IntList = []
FloatList = []
for i in NumList:
  typobj = type(i)
  if typobj == str:
    StrList.append(i)
  elif typobj == float:
    FloatList.append(i)
  elif typobj == int:
    IntList.append(i)
print(f"StrList = {StrList}")
print(f"IntList = {IntList}")
print(f"FloatList = {FloatList}")

When "#", ".", etc..are included, all of them went to string. They should be in string.

Enter string, int, float with the list : [1, 4.9, 4, "Five", 6, 7, "Eight", "#" ,2, 15, "$", "."]
StrList = ['[', '1', ',', ' ', '4', '.', '9', ',', ' ', '4', ',', ' ', '"', 'F', 'i', 'v', 'e', '"', ',', ' ', '6', ',', ' ', '7', ',', ' ', '"', 'E', 'i', 'g', 'h', 't', '"', ',', ' ', '"', '#', '"', ' ', ',', '2', ',', ' ', '1', '5', ',', ' ', '"', '$', '"', ',', ' ', '"', '.', '"', ']']
IntList = []
FloatList = []

CodePudding user response:

All input from

x = input("Enter input: ")

is taken as a string unless otherwise specified. if you are wanting extract strings integers and floats from the list shown above you should use.

parsed_list = [i.strip("'") for i in input_list.split(",")]
for i in parsed_list:
    try:
        int_list.append(int(i))
    except ValueError:
        try:
            float_list.append(float(i))
        except:
            str_list.append(i)

as a note variables in python should be written in snake case. Classes and objects are usually denoted by camel case so you will make it a lot easier for your maintenance programmer by following the convention (barring any company policy to the country)

CodePudding user response:

Use ast.literal_eval to making list from str input

from ast import literal_eval

NumList = literal_eval(NumList)

Use list comprehension for separating

StrList = [i for i in NumList if type(i) == str]
IntList = [i for i in NumList if type(i) == int]
FloatList = [i for i in NumList if type(i) == float]

But better to change interaction instead of literal_eval:

# creating an empty list
lst = []
  
# number of elements as input
n = int(input("Enter string, int, float : "))
  
# iterating till the range
for i in range(0, n):
    ele = int(input())
  
    lst.append(ele) # adding the element
      
print(lst)

CodePudding user response:

This is because input() reads everything in as string objects. You need to try casting the user input to float or int. If it works, it is a valid int, otherwise it will raise an ValueError and you have to try another data type. See here: Convert any user input to int in Python

CodePudding user response:

You can define another function or simply use a loop to remove unwanted characters from your string list.

str_list = ['[', '1', ',', ' ', '4', '.', '9', ',', ' ', '4', ',', ' ', '"', 'F', 'i', 'v', 'e', '"', ',', ' ', '6', ',', ' ', '7', ',', ' ', '"', 'E', 'i', 'g', 'h', 't', '"', ',', ' ', '"', '#', '"', ' ', ',', '2', ',', ' ', '1', '5', ',', ' ', '"', '$', '"', ',', ' ', '"', '.', '"', ']']

# Define unwated character's list:
not_wanted_char_list = [',', '"', '[', ']'] # etc...

# Initialize for-loop:
for not_wanted_char in not_wanted_char_list
    str_list.remove(not_wanted_char)

And After you do that, you can then create another for-loop which joins the letters to form words (eg. 'Five' and 'Eight'), until it reaches either a capital letter or a number, which will mark the end of your word.

  • Related