I'm quite new to programming and working on a challenge. I have a string of a hundred 50-digit numbers (they aren't separated in any way) and want to take out the first digit from each number. How can I do this? Should I try to index the correct numbers, or maybe convert the string into a numpy array and extract the first column somehow? Thanks for the help!
2 Answers
If you've a string of N
numbers, each of length L
, and you want to extract the first digit of each number - you'll notice that the first digit you're looking for is at index 0, the next digit is at index L
, the third is at index L+L
and so on.
Notice the pattern? You start from index 0, and step by the length of each number. Python has a special syntax for this, stepping using slices
So if you had a string like 12345678
, where you have 2 numbers, each of length 4 - you'd want to extract 1
and 5
(the first digit of the 2 numbers), you can do-
>>> '12345678'[::4]
'15'
If you want the result in a list, instead of a string, cast the result to a list
-
>>> list('12345678'[::4])
['1', '5']

- 5,315
- 2
- 15
- 41
-
Thank you, I should have thought of that! I was also wondering, if I was to take the first 2 or 3 digits in the number instead, how do I do that? – Marta Jan 31 '21 at 14:47
-
@martarel Welcome to SO! Note that it's [encouraged to not post "thank you" comments](https://meta.stackexchange.com/questions/126180/is-it-acceptable-to-write-a-thank-you-in-a-comment). If you feel obliged to thank an answer, upvote or mark as accepted instead. – Chase Jan 31 '21 at 14:51
Use the range built in method of python. It takes a start, stop and step value. If the step value is skipped, it defaults to 1
I've used it twice in the code below. First to make some random test data and secondly to extract the 50th digits, which will be the "first digit" in your 50 digit sets
import random
# generate 50,000 random digits
a=""
for i in range(1,50000):
a=a+"%d"%random.randint(1,9)
# pick out every 50th, starting at zero
for i in range(0,50000,50):
print(a[i])

- 32,923
- 5
- 39
- 63