python - 有没有更有效的方法来扩展字符串?

标签 python string loops

<分区>

有没有人知道一种更有效的方法来扩展字符串,例如 fred,使其成为字符串 plaintext 的长度 - 这样 fred 会变成 fredfredf - 比这个好吗?

# key='fred', msg='plaintext'?

def keypad(key, msg):
    while len(key) < len(msg):
        key += key
    key = key[:len(msg)]
    return key

最佳答案

使用islice + cycle来自 itertools:

from itertools import islice, cycle

key = 'fred'
msg = 'plaintext'

print(''.join(islice(cycle(key), len(msg))))
# fredfredf

关于python - 有没有更有效的方法来扩展字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57535523/

相关文章:

java - 替换第一个和最后一个字符?

无法返回 0,即使字符串为 null

python - “变量”或 'variable is not None'

python - 将 Flask 应用程序部署到 Heroku - web.1 : crashed

string - 如何像 Python 在 Perl 6 中那样对字符串进行切片?

javascript - 如何在javascript中获取php while循环

python - 使用数组数据遍历 2 个列表

arrays - 根据阵列中每个I时间的持续时间播放快速声音

python - 计算Series的局部时间导数

Python nltk 无法在 Pycharm 上运行