Convert all strings in a list to int

前端 未结 4 783
夕颜
夕颜 2020-11-22 01:49

In Python, I want to convert all strings in a list to integers.

So if I have:

results = [\'1\', \'2\', \'3\']

How do I make it:

4条回答
  •  刺人心
    刺人心 (楼主)
    2020-11-22 02:09

    Here is a simple solution with explanation for your query.

     a=['1','2','3','4','5'] #The integer represented as a string in this list
     b=[] #Fresh list
     for i in a: #Declaring variable (i) as an item in the list (a).
         b.append(int(i)) #Look below for explanation
     print(b)
    

    Here, append() is used to add items ( i.e integer version of string (i) in this program ) to the end of the list (b).

    Note: int() is a function that helps to convert an integer in the form of string, back to its integer form.

    Output console:

    [1, 2, 3, 4, 5]
    

    So, we can convert the string items in the list to an integer only if the given string is entirely composed of numbers or else an error will be generated.

提交回复
热议问题