Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,938 questions

51,875 answers

573 users

How to split a string into chunks of two characters each in Python

2 Answers

0 votes
def split_string_into_chunks(string, chunk_size):
    chunks = []
    length = len(string)

    for i in range(0, length, chunk_size):
        # Extract substring of chunk_size or remaining characters
        chunks.append(string[i:i + chunk_size])

    return chunks

string = "abcdefghijk"
chunk_size = 2

chunks = split_string_into_chunks(string, chunk_size)

print("Chunks of two characters:")
for chunk in chunks:
    print(chunk)



'''
run:

Chunks of two characters:
ab
cd
ef
gh
ij
k

'''

 



answered Mar 30, 2025 by avibootz
0 votes
def split_string_into_chunks(string):
    # Splits a string into chunks of two characters each.
    chunks = [string[i:i + 2] for i in range(0, len(string), 2)]
    
    return chunks


string = "abcdefghijk"
chunks = split_string_into_chunks(string)
print(chunks) 

string = "abcdefghijkl"
chunks2 = split_string_into_chunks(string)
print(chunks2) 

string = ""
chunks3 = split_string_into_chunks(string)
print(chunks3) 

string = "a"
chunks4 = split_string_into_chunks(string)
print(chunks4)



'''
run:

['ab', 'cd', 'ef', 'gh', 'ij', 'k']
['ab', 'cd', 'ef', 'gh', 'ij', 'kl']
[]
['a']

'''

 



answered Mar 30, 2025 by avibootz
...