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

2024-04-19 23:36:37 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在处理一个python项目,在这个项目中,我需要包括一个输入和另一个值(将被操作)。在

例如, 如果我输入字符串'StackOverflow',以及要对'test'进行操作的值,程序将通过重复和修剪字符串使可操作变量等于字符数。这意味着'StackOverflow'和{}将输出{}。在

这是我目前掌握的代码:

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

{但我不确定如何有效地使用cd6}来操作剩余的循环。任何帮助都将不胜感激,谢谢。在


Tags: to项目字符串代码test程序aninput
3条回答

这里有一些好的,Python式的解决方案。。。但是如果您的目标是理解while循环而不是itertools模块,那么它们就没有帮助了。在这种情况下,也许您只需要考虑如何使用+操作符来增长一个字符串,并用一个切片来修剪它:

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的答案)。在

一种itertools.cycle方法:

from itertools import cycle

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

如果您提到纯文本-a是您的密钥,b将是明文中的字符-因此您可以使用它来方便地管理配对。。。在

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

^{pr2}$

试试这样的方法:

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,并且在python中,一个X和一个字符串的乘法会将字符串X次连接起来。在

输出:

^{pr2}$

您还可以在字符串上创建一个无限循环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('stackoverflow'))]
>>> ''.join(gen_it)
'testtesttestt'

相关问题 更多 >