简体   繁体   English

如何将字符串拆分为 6 个字符的块?

[英]How do I split a string into chunks of 6 characters?

I am trying to make a Base 64 encoder in python, where you enter a message and it converts it to Base 64.我正在尝试在 python 中制作 Base 64 编码器,您可以在其中输入一条消息并将其转换为 Base 64。

After converting each letter in the message to binary, the code returns a string of the binary digits, separated with no spaces.将消息中的每个字母转换为二进制后,代码返回一串二进制数字,中间没有空格。 The next step is to split the string of binary into chunks of 6 and append each one to a list in order (any remainders at the end of a string which are <6 characters long are just appended to the end of the list).下一步是将二进制字符串拆分为 6 块和 append 的块,每个块按顺序排列到列表中(字符串末尾的长度小于 6 个字符的任何剩余部分仅附加到列表的末尾)。

The code below is responsible for returning just the string of binary, with no spaces:下面的代码负责只返回二进制字符串,没有空格:

message = input("Message: ")
n = []
for i in message:
    a = ord(i)
    binary = bin(a)[2:]
    n.append(binary)
bin_message = ", ".join(n).replace(",", "").replace(" ", "")

I tried the solution below, but it doesn't take into account any remainders, and also has a bug where the last element of the list gets its last t chopped off:我尝试了下面的解决方案,但它没有考虑任何余数,并且还有一个错误,即列表的最后一个元素被砍掉了最后一个 t:

message = input("Message: ")
n = []
for i in message:
    a = ord(i)
    binary = bin(a)[2:]
    n.append(binary)
bin_message = ", ".join(n).replace(",", "").replace(" ", "")
chunks = []
index = -6
length = len(bin_message)
for j in range(length//6):
    index += 6
    chunk = bin_message[index:index + 6]
    chunks.append(chunk)
print(chunks)

This is a more detailed explanation:这是更详细的解释:

If the message is "And", it converts each character to its decimal ascii value;如果消息是“And”,它将每个字符转换为其十进制 ascii 值; now the message is 65 110 100. Next, the code uses a for loop to convert each ascii value to a binary number, removes the "0b" prefix, and appends it to a list.现在消息是 65 110 100。接下来,代码使用 for 循环将每个 ascii 值转换为二进制数,删除“0b”前缀,并将其附加到列表中。 Then, any spaces and commas are removed so you are left with just the string.然后,删除所有空格和逗号,因此您只剩下字符串。 So, "And" becomes "100000111011101100100".所以,“和”变成了“100000111011101100100”。 Now, it needs to split this string into chunks of 6, and append the remaining 3 numbers onto the end: ["100000", "111011", "101100", "100"].现在,它需要将此字符串分成 6 个块,并将 append 剩余的 3 个数字放在末尾:[“100000”、“111011”、“101100”、“100”]。 That is the part I am stuck on.那是我坚持的部分。

Turning a string into chunks can be done by using range to its full potential with the start , end and step arguments.将字符串变成块可以通过使用range来完成,包括startendstep arguments。

s = "Lorem ipsum dolor sit amet, consetetur sadipscing elitr"

chunks = []

for i in range(0, len(s), 6):
    chunks.append(s[i:i+6])

print(chunks)

# ['Lorem ', 'ipsum ', 'dolor ', 'sit am', 'et, co', 'nsetet', 'ur sad', 'ipscin', 'g elit', 'r']

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

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