0

I have an exercise where i have an input of a number with six characters

input = 567809

How do i extract 2 digits from the middle of this? like, i know that i can get the first two numbers if i use

first2 = int(str(input)[:2]) also for the first 4 numbers if i want to

But how do i get the 2 last and the 2 middle numbers??

i want to have an proper code where the input is segmented like :

first2 = 56
middle = 78
last = 09
  • Does this help: https://stackoverflow.com/questions/18854620/whats-the-best-way-to-split-a-string-into-fixed-length-chunks-and-work-with-the ? – user19513069 Aug 18 '22 at 14:31

3 Answers3

1

The below method should work for all string sizes

s = '567809'
last_two = s[-2:] # gives you '09'
middle = s[len(s)//2-1:len(s)//2+1] # '78'
Himanshu Poddar
  • 7,112
  • 10
  • 47
  • 93
0

for 6 digit number

first2, number = number%100, number//100
middle, number = number%100, number//100
last = number
sahasrara62
  • 10,069
  • 3
  • 29
  • 44
0

If it's always a 6-char input, then you can do middle = my_list[2:4].

This syntax says, "get me all the elements of the list, from the 2nd element up to the 4th, not including the 4th". (remembering that python indexes from zero)

More generally, for lists of different sizes, you'd go with a strategy of finding the index of the middle element by doing middle_element_index = int(len(my_list)/2). Bear in mind "middle" means different things depending if the list has an even or odd number of elements.

p.s., careful not to use input = in python because "input" does something else, and you'll overwrite it.

Alan
  • 1,746
  • 7
  • 21