根据另一个字符串的长度操作字符串重复

Manipulating string to repeat based on the length of another string

我正在做一个 python 项目,我需要在其中包含一个输入和另一个值(将被操纵)。

例如, 如果我输入字符串 'Whosebug' 和要操作的值 'test',程序将通过重复和修剪字符串使可操作变量等于字符数。这意味着 'Whosebug''test' 将输出 'testtesttestt'.

这是我目前的代码:

originalinput = input("Please enter an input: ")
manipulateinput = input("Please enter an input to be manipulated: ")
while len(manipulateinput) < len(originalinput):

并且我正在考虑包括一个 for 循环来继续其余部分,但我不确定我将如何使用它来有效地操纵字符串。任何帮助将不胜感激,谢谢。

尝试这样的事情:

def trim_to_fit(to_trim, to_fit):
     # calculate how many times the string needs
     # to be self - concatenated
     times_to_concatenate = len(to_fit) // len(to_trim) + 1
     # slice the string to fit the target
     return (to_trim * times_to_concatenate)[:len(to_fit)]

它使用 slicing,并且 X 和 python 中的字符串相乘将字符串连接 X 次。

输出:

>>> trim_to_fit('test', 'Whosebug')
'testtesttestt'

您还可以在字符串上创建一个无限循环 generator

# improved by Rick Teachey
def circular_gen(txt):
    while True:
        for c in txt:
            yield c

并使用它:

>>> gen = circular_gen('test')
>>> gen_it = [next(gen) for _ in range(len('Whosebug'))]
>>> ''.join(gen_it)
'testtesttestt'

一种itertools.cycle方法:

from itertools import cycle

s1 = 'Test'
s2 = 'Whosebug'
result = ''.join(a for a, b in zip(cycle(s1), s2))

鉴于您提到 纯文本 - a 是您的密钥,而 b 将是明文中的字符 - 因此您也可以方便地使用它操纵配对...

我猜你最终会得到这样的结果:

result = ''.join(chr(ord(a) ^ ord(b)) for a, b in zip(cycle(s1), s2))
# '\x07\x11\x12\x17?*\x05\x11&\x03\x1f\x1b#'
original = ''.join(chr(ord(a) ^ ord(b)) for a,b in zip(cycle(s1), result))
# Whosebug

您需要的是一种方法,可以从 manipulateinput 字符串中反复提取每个字符,这样您就不会 运行 超出字符范围。

您可以通过将字符串相乘来实现此目的,以便根据需要重复多次:

mystring = 'string'
assert 2 * mystring == 'stringstring'

但是要重复多少次呢?那么,您可以使用 len 获得字符串的长度:

assert len(mystring) == 6

因此,为了确保您的字符串至少与另一个字符串一样长,您可以这样做:

import math.ceil # the ceiling function
timestorepeat  = ceil(len(originalinput)/len(manipulateinput))
newmanipulateinput = timestorepeat * manipulateinput

另一种方法是使用整数除法,或 //

timestorepeat  = len(originalinput)//len(manipulateinput) + 1
newmanipulateinput = timestorepeat * manipulateinput

现在您可以使用 for 循环而不 运行 排除字符:

result = '' # start your result with an empty string 
for character in newmanipulateinput: 
    # test to see if you've reached the target length yet
    if len(result) == len(originalinput):
        break
    # update your result with the next character
    result += character 
    # note you can concatenate strings in python with a + operator 
print(result)

这里有一些很好的 Pythonic 解决方案...但是如果您的目标是理解 while 循环而不是 itertools 模块,它们将无济于事。在那种情况下,也许您只需要考虑如何使用 + 运算符和 trim 切片来增长字符串:

originalinput = input("Please enter an input: ")
manipulateinput = input("Please enter an input to be manipulated: ")
output = ''
while len(output) < len(originalinput):
    output += manipulateinput
output = output[:len(originalinput)]

(请注意,这种字符串操作在实际 Python 代码中通常不被接受,您可能应该使用其他方法之一(例如,Reut Sharabani 的回答)。