Split long strings

Asked 2 years ago, Updated 2 years ago, 118 views

ABCDEFGHIJKLMN

The string ABC DEF GHI... in an expression

I'd like to make a list of 3 pieces each, what should I do?

I'm trying to solve it with a FOR statement.

python string divide

2022-09-22 10:48

1 Answers

a = "abcdefghijklm"

def split_by_for(s, n):
    result = []
    for i in range(0, len(s), n):
        result.append(s[i:i+n])
    return result

def split_by_list_comprehension(s, n):
    return [s[i:i+n] for i in range(0, len(s), n)]

def split_by_recursion(s, n):
    return [s[:n]] + split_by_recursion(s[n:], n) if s else []

split_by_rec_lambda = lambda s, n: [s[:n]] + split_by_rec_lambda(s[n:], n) if s else []

print(split_by_for(a, 3))
print(split_by_list_comprehension(a, 3))
print(split_by_recursion(a, 3))
print(split_by_rec_lambda(a, 3))


2022-09-22 10:48

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.