Get first number from string list

Viewed 26

I've got a list that currently looks like this ['15 12 6', '7 20 9 10', '13 17', '3']

I want to be able to get the first number from each index (15,7,13,3), but I'm not sure how. I know how to get the first digit of each number, but I don't know what to do for the numbers with 2 digits.

2 Answers

To get the first number, you should split the string by space.

Try this:

nums = ['15 12 6', '7 20 9 10', '13 17', '3']
res = [int(x.split(' ')[0]) for x in nums] # [15, 7, 13, 3]

First you'll want to get each index. As each number is split by spaces, you'll need to split the code at every space. Then you'll take the first index created by the split function.

for i in list:
    x = i.split(' ')[0]
    print(x) 
Related