簡體   English   中英

如何拆分不同長度的字符串?

[英]How to split strings of different lengths?

我正在嘗試制作自己的加密算法,但我不知道如何將具有不同長度的字符串拆分為列表。 這是我的代碼:

import random
from calculations import test_divisibility  # This is a function that returns which numbers can divide evenly into the given number

def encrypt(text):
    div_by = test_divisibility(len(text))
    if div_by is None:  # If length of string is a prime number, figure out an alternate way to encrypt the string.
        pass

    divisor = random.choice(div_by)

original = "This is the string to be hashed into the untitled hashing algorithm."

print(encrypt(original))

function 將從返回的列表中選擇一個隨機數,並將該數字除以要加密的消息長度。 該數字的結果應該是字符串應該具有的切片數。

以字符串"This is the string to be encrypted into my custom-made algorithm"為例。 如果將字符串傳遞給 function,您會發現字符串的長度可以被 2、4 和 8 整除。那么隨機 function 應該選擇其中一個數字並將字符串的長度除以該數字。 結果將是字符串應具有的切片數。

這是一個 function ,它將一個字符串分成c大小相等的塊,最后一個塊包含任何溢出:

def split_str(strng, c):
    l = len(strng) // c
    r = [strng[n * l:(n + 1) * l] for n in range(c - 1)]
    r.append(strng[(c - 1) * l:])
    return r

s = 'Now is the time for all good men to come to the aid'

print(split_str(s, 4))

結果:

['Now is the t', 'ime for all ', 'good men to ', 'come to the aid']

如果您知道字符串將始終均分,則可以稍微簡化 function。 那么它就是:

def split_str(str, c):
    l = len(str) // c
    r = [str[n*l:(n+1)*l] for n in range(c)]

rest 只是數學,聽起來你已經掌握了。 或者您需要幫助找到數字的因數? 我知道已經有很多關於這個的問題。

這里有一點不同,它將字符串分成盡可能多的相同大小的組,並將多余的部分放入額外的組中。 如果字符串的長度是組大小的精確倍數,則不會發生這種情況。

from itertools import zip_longest

_filler = object()  # Value which couldn't be in data.

def grouper(n, iterable):
    for result in zip_longest(*[iter(iterable)]*n, fillvalue=_filler):
        yield tuple(v for v in result if v is not _filler)

n = 4
s = 'Now is the time for all good men to come to the aid'
group_len = len(s) // n
result = list(''.join(group) for group in grouper(group_len, s))
print(result)

Output

['Now is the t', 'ime for all ', 'good men to ', 'come to the ', 'aid']

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM