0

Which is the best pythonic way to split the strings into substring with some index?

word = "jungle" expected output : ju ng le My attempt : https://code.sololearn.com/ceV5Hu1E5d96/?ref=app

18th Feb 2021, 9:02 AM
Ratnapal Shende
Ratnapal Shende - avatar
9 Respostas
+ 3
Check this out, just run and enter the substring ("chunk size"). It returns a list of whatever you entered sized substrings of supplied string. Try it with 2 and then w/ 3 Ratnapal Shende Check it out now. It will take any number and seperate the string into chunks of that size. Adding dashes to compensate the missing characters on the last chunk if needed https://code.sololearn.com/cZlPH7HEH356/?ref=app
18th Feb 2021, 9:50 AM
Slick
Slick - avatar
+ 3
Using list comprehension combined with range definition. https://code.sololearn.com/cig6WaHM9HD1/?ref=app
18th Feb 2021, 12:00 PM
Ipang
+ 2
No problem! And which module do you mean?
18th Feb 2021, 10:08 AM
Slick
Slick - avatar
+ 2
imported sys just to exit when i want. and imported math so i could round up. its important to round up in order for the code to get and split the entire word
18th Feb 2021, 10:14 AM
Slick
Slick - avatar
+ 2
with re module only: import re print(re.findall(r'.{1,'+str(chunk_size)+'}',word))
18th Feb 2021, 10:37 AM
visph
visph - avatar
+ 2
Ratnapal Shende do you know no regular expressions? first argument of re.findall is the pattern string to be compiled, dynamically build... it result as ".{1,n}" where n is the chunck size... dot search for any character * (1 to n) times... re.findall(".{1,3}",text) will return all 3 length chunck + eventual less than 3 final chunck ;)
27th Feb 2021, 11:05 AM
visph
visph - avatar
0
Slick Thank you bro! bro any simplest way other than using module ?
18th Feb 2021, 10:06 AM
Ratnapal Shende
Ratnapal Shende - avatar
0
without using any module
18th Feb 2021, 10:10 AM
Ratnapal Shende
Ratnapal Shende - avatar
0
visph your code seems complicated for me please explain this syntax re.findall(r'.{1,'+str(chunk_size)+'}',word)) ' } ' quotes ?? 🤔🤔
27th Feb 2021, 8:08 AM
Ratnapal Shende
Ratnapal Shende - avatar