0

I need to extract a two digit number from a string in python3.

** e.g. string is "1234" and I want the middle two numbers so I get 23.**

This isn't limited to just four letters, it could be hundreds.

Please could someone help?

Thank you as always!

5
  • 1
    Is the string always four characters? If not, which digits would you use from, say, a five digit string 12345? Commented Jul 17, 2018 at 12:23
  • Always drop the first and last characters? Or always skip the first, then use the next two only? Or use two before the last character? Commented Jul 17, 2018 at 12:23
  • @PatrickHaugh it is not always four characters, it can be up to a few hundred. doctorlove, when it's a few hundred it, becomes complicated trying to drop the other numbers/skipping certain ones. Worst case scenario I can do that but I just wanted to see if there is a more efficient way. thanks Commented Jul 17, 2018 at 12:41
  • The simplest way is probably to make a list of the index you need and use a list comprehension on the string. Commented Jul 17, 2018 at 13:10
  • So what do you want as your result for '1234567' ? Commented Jul 17, 2018 at 14:49

3 Answers 3

1

I have tried the following line of code and it works for me.

value = '1234'

print(value[1:-1])

Hope this helps.

Edit:

With some more char in it.

value = '1234567'

m = len(value)//2

print(value[m:m+2])
Sign up to request clarification or add additional context in comments.

Comments

0

To extract two digits from the string "1234"

str function can be used.

Code:

 stringparse="1234"
 twodigit= stringparse[1]+stringparse[2]
 print(twodigit)

Output Out[180]: '23'

1 Comment

Thank you very muc!
0

According to a quick Google search (this website), you should do:

String = "1234" ChoppedString = String[1:3] #Remember, the first letter is 0, the second is 1, etc. print(ChoppedString)

The [1:3] bit just means 'Start at the first letter, then get everything up to (but excluding) the second one.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.