[英]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)
输入 "99/100" 时,我希望它打印 ["99", "/", "100"] 而不是 ['9', '9', '/', '1', '0', '0' ]
您可以为此使用“.split”,例如:
thing1 = "abcdef"
thing1.split("c")
给出输出:
['ab', 'def']
如果您很无聊并且喜欢为自己的兴趣与一些意大利面条式代码作斗争,那么自己编写类似于“.split()”的代码可能是一个有趣的挑战。 这样做可以让你思考 Python 是如何工作的,并尝试在最小的 big-O 中实现它可以向你介绍一些关于字符串、数组和算法效率的有趣内容。
如果要保留分隔符,如问题所示,可以使用re
模块。
import re
fraction = input("Enter: ")
print(re.split("(/)", fraction))
它应该使用partition
方法而不是split
,因为使用split
将省略分隔符参数。
"99/100".partition('/')
#('99', '/', '100')
对于嵌套分数,建议使用其他策略, re
,...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.