简体   繁体   English

在 python 中,我如何迭代一个字符串,在不同的位置将其拆分为 go?

[英]In python how can I iterate through a string splitting it at different spots as I go?

I'm trying to write a quick solve for Kaprekar number's to show a friend of mine how easy it is to implement something like this in Python.我正在尝试为 Kaprekar 数编写一个快速解决方案,以向我的朋友展示在 Python 中实现这样的事情是多么容易。 I know how to do all the steps except for iterating through the squared number as a string.除了将平方数作为字符串进行迭代之外,我知道如何执行所有步骤。 For example 45 is a Kaprekar number because例如 45 是一个 Kaprekar 数,因为

45 ** 2 = 2025 and 20 + 25 = 45 45 ** 2 = 2025 和 20 + 25 = 45

What I'm trying to write is code that would take the result of 45 ** 2 = 2025 and let me iterate over the combinations like我正在尝试编写的代码将采用 45 ** 2 = 2025 的结果并让我遍历组合,例如

['2', '025'] ['2', '025']

['20', '25'] ['20', '25']

['202', '5'] ['202', '5']

>>> s = '2025'
>>> for i in range(1, len(s)):
...   print s[:i], s[i:]
... 
2 025
20 25
202 5

I will spend a couple of extra days in purgatory for answering a math question already answered by Ignacio, but you may also experiment with some variant of:我将在炼狱中多花几天时间来回答 Ignacio 已经回答的数学问题,但您也可以尝试以下一些变体:

>>> a = 2025
>>> for i in range(1,4):
...     print a / 10**i, a % 10**i
... 
202 5
20 25
2 25

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM