Python Input comma-separated elements, convert into list and print

Here, we will figure out how to change over comma isolated components into list utilizing Python? Here, we will enter comma separate components and convert into a list of integers.

Info comma isolated components (integers), and changes over it into the list in Python.

Example:

    Input:
    Enter comma separated integers: 10,20,30,40,50

    Output:
    list:  ['10', '20', '30', '40', '50']
    List (after converted each element to int)
    list (li) :  [10, 20, 30, 40, 50]

Rationale:

  • Info a comma – isolated string utilizing raw_input() strategy.
  • Split the components delimited by comma (,) and appoint it to the list, to a part string, use string.split() strategy.
  • The changed over list will contain string components.
  • Convert components to correct integers:
    • Cross each number in the list by utilizing for…in circle.
    • Convert number (which is in string design) to the integer by utilizing int() technique.
  • Print the list.

Program:

# input comma separated elements as string 
str = str (raw_input ("Enter comma separated integers: "))
print "Input string: ", str

# conver to the list
list = str.split (",")
print "list: ", list

# convert each element as integers
li = []
for i in list:
	li.append(int(i))

# print list as integers
print "list (li) : ", li

Output:

    Enter comma separated integers: 10,20,30,40,50
    Input string:  10,20,30,40,50
    list:  ['10', '20', '30', '40', '50']
    list (li) :  [10, 20, 30, 40, 50]

Leave a Comment

error: Alert: Content is protected!!