Home > front end >  Trying to input a fraction and split it into a list but it causes problem when the numbers are more
Trying to input a fraction and split it into a list but it causes problem when the numbers are more

Time:07-18

fraction = list(input("Enter: "))
print(fraction)

When Inputting "99/100" I wanted it to print ["99", "/", "100"] not ['9', '9', '/', '1', '0', '0']

CodePudding user response:

You can use ".split" for this, for example:

thing1 = "abcdef"
thing1.split("c")

Gives the output:

['ab', 'def']

If you're bored and fancy fighting some spaghetti code for your own interest, it can be a fun challenge to code something equivalent to ".split()" yourself. Doing so gets you thinking about how Python works and trying to do it in the smallest big-O can introduce you to some interesting stuff about strings, arrays, and algorithm efficiency.

CodePudding user response:

If you want to keep the delimiter, as shown in the question, you can use the re module.

import re

fraction = input("Enter: ")
print(re.split("(/)", fraction))

CodePudding user response:

It should be used partition method and not split since with split will omit the separator parameter.

"99/100".partition('/')
#('99', '/', '100')

For nested fractions other strategies are recommended, re,...

  • Related