[英]Trying to input a fraction and split it into a list but it causes problem when the numbers are more than 1 digit
fraction = list(input("Enter: "))
print(fraction)
When Inputting "99/100" I wanted it to print ["99", "/", "100"] not ['9', '9', '/', '1', '0', '0']输入 "99/100" 时,我希望它打印 ["99", "/", "100"] 而不是 ['9', '9', '/', '1', '0', '0' ]
You can use ".split" for this, for example:您可以为此使用“.split”,例如:
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.如果您很无聊并且喜欢为自己的兴趣与一些意大利面条式代码作斗争,那么自己编写类似于“.split()”的代码可能是一个有趣的挑战。 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.这样做可以让你思考 Python 是如何工作的,并尝试在最小的 big-O 中实现它可以向你介绍一些关于字符串、数组和算法效率的有趣内容。
If you want to keep the delimiter, as shown in the question, you can use the re
module.如果要保留分隔符,如问题所示,可以使用re
模块。
import re
fraction = input("Enter: ")
print(re.split("(/)", fraction))
It should be used partition
method and not split
since with split
will omit the separator parameter.它应该使用partition
方法而不是split
,因为使用split
将省略分隔符参数。
"99/100".partition('/')
#('99', '/', '100')
For nested fractions other strategies are recommended, re
,...对于嵌套分数,建议使用其他策略, re
,...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.