0

I am trying to replace a list of string into a list of int.

I was given a list looks something like this:

List = ["1 min", "12 min", "721 min"]

And I would like to convert it to something like this:

[1, 12, 721]

My thought is to use for to loop for every element, i.e.

for i in List:
   list[i] = int(i)

But since the time is not constant, it might be 1 digit number, 2 digit or 3... I would love to know if there is a way to modify the element such that whenever there exist a space " " in the element, I would delete the rest of the substring of that string? (E.g. "1 min" becomes "1").

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
  • 1
    Does this answer your question? [Split string on whitespace in Python](https://stackoverflow.com/questions/8113782/split-string-on-whitespace-in-python) – mkrieger1 Apr 15 '22 at 16:27

5 Answers5

1

Try in this way:

List = ["1 min", "12 min", "721 min"]
output = []
for i in List:
    elems = i.split()
    output.append(int(elems[0]))
print(output)
#[1,12,721]

If you want to modify the current list, do it in this way:

List = ["1 min", "12 min", "721 min"]
for i in range(len(List)):
    elems = List[i].split()
    List[i] = int(elems[0])
print(List)
SAI SANTOSH CHIRAG
  • 2,046
  • 1
  • 10
  • 26
0

You could use i.split(' ')[0] It will split the string into an array breaking it up on the spaces, then you just grab the first element in the array.

bthalpin
  • 24
  • 5
0

List[i] = int(i) int(i) will convert the string into number but it cannot convert the alphabets so it will throw an error. So you can split the string using the whitespaces and the first element will be the number and you can use it

List = ["1 min", "12 min", "721 min"]

for i in range(len(List)) :
    
    temp = List[i].split(" ")[0]
    
    List[i] = int(temp)
    
print(List)
0

You could try this small function


exampleList = ["1 min", "12 min", "721 min"]

def modifyList(li):
    # remove "min" from each element of li
    for i in range(len(li)):
        li[i] = li[i].replace(" min", "")
        li[i] = int(li[i])
    
    print(li)
    
modifyList(exampleList)

Hope this helps!

0

The solution by @Santosh is excellent. But if you want it be more rigorous you can use regex to get the numbers out like this

import re

a = ["1 min", "12 min", "721 min"]

b = [int(re.findall(r'\d+', x)[0]) for x in a]

This is a bit better approach if the number and strings are not always separated by delimeters.

exilour
  • 516
  • 5
  • 12