简体   繁体   中英

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.

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).

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:

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; 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. Then, any spaces and commas are removed so you are left with just the string. So, "And" becomes "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"]. 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.

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']

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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