Home > Software engineering >  How to split a string in to list where the number of string in the list is defined?
How to split a string in to list where the number of string in the list is defined?

Time:04-28

So if I have a string:

s = "this is just a sample string"

I want to obtain a list of 3 characters each:

l = ["thi", "s i", "s j", "ust", " a ", ...]

CodePudding user response:

Don't use list for a variable name because it's a keyword in Python. Here's how you can do it:

string =  "this is just a sample string"
l = [string[i:i 3] for i in range(0,len(string),3)]
print(l)

Output:

['thi', 's i', 's j', 'ust', ' a ', 'sam', 'ple', ' st', 'rin', 'g']

CodePudding user response:

you can use list comprehension

string = "this is just a sample string"
n = 3
[string[i:i n] for i in range(0, len(string), n)]

output

chunks = ['thi', 's i', 's j', 'ust', ' a ', 'sam', 'ple', ' st', 'rin', 'g']

CodePudding user response:

With more-itertools:

from more_itertools import chunked
list = [''.join(chunk) for chunk in chunked(string, 3)]

CodePudding user response:

You can match 1-3 characters using the dot to match any character including a space and a quantifier {1,3}

import re

print(re.findall(r".{1,3}", "this is just a sample string"))

Output

['thi', 's i', 's j', 'ust', ' a ', 'sam', 'ple', ' st', 'rin', 'g']

If you don't want the single char match for 'g' then you can use .{3} instead of {1,3}

  • Related