编写一个函数,将字符串“s”作为参数,拆分为,并返回一个元组(左、中、右)。如果字符串的长度不能被3平均整除,那么函数应该尽可能平均地分割字符串。你知道吗
我试过使用for循环和string替换,strip函数,显然不起作用。。。我不知所措。我的代码现在输出3的所有东西
def trisect(s):
print(tuple([s[i:i+3] for i in range(0, len(s), 3)]))
s = input("what is your string: ")
trisect(s)
预期结果:输入:"123456789012"
输出:('1234', '5678', '9012')
实际结果:输入:"123456789012"
输出:('123', '456', '789', '012')
可以使用
len(s)
获取字符串的长度,然后使用len(s) // 3
(//
执行整数除法)获取节的长度。你知道吗从那里,只需根据需要切片:
编辑:
使用
length = round(len(s) / 3)
代码:
输出:
编辑:一种广义的方法。你知道吗
起初,我认为这是一个重复,但现有的线程似乎没有考虑到“尽可能均匀”的要求。使用
textwrap.wrap
、zip
和大多数itertools解决方案会在最后留下一个悬空的不均匀块。这个解决方案从前面分块n
和焊盘的任意值。你知道吗方法是取iterable长度的商和余数,并开始按所需的块大小进行迭代。对于每个区块,如果有余数,则向区块添加1。按块大小+1递增步长,并递减余数。如果没有剩余,则正常生成块。你知道吗
下面是函数和测试代码:
输出摘录:
现在,编写
trisect
函数如下所示:相关问题 更多 >
编程相关推荐