How do I separate a list of letters into groups of n? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

How do I separate a list of letters into groups of n?

I'd like to take a message, and after removing the spaces, separate the letters into subgroups of n length. If I was to input a message of `hello world hello world` and set n to 7, it should output `hellowo-rldhell-oworld`.

25th Nov 2019, 4:35 AM
August Borne
August Borne - avatar
4 Answers
+ 5
basically logic here is, loop through the string itself, make a counter to check number of letters taken if it is 7 already then you should add a "-" or else add letter itself. def sep(s, no): c = 0 n = "" for i in s: if(i == " "): continue if(c == no): n += "-" c = 0 else: n += i c = c + 1 return n v = sep("Hello world Hello World", 7) print(v)
25th Nov 2019, 5:06 AM
Raj Chhatrala
Raj Chhatrala - avatar
+ 2
import re def myfunc(mystring, myint): return '-'.join(re.findall(r"\w{1," + str(myint) + "}", mystring.replace(" ", ""))) print(myfunc("hello world hello world", 7))
25th Nov 2019, 6:52 PM
rodwynnejones
rodwynnejones - avatar
+ 1
You can also calculate the number of groups needed ahead of time. Then you can use for loop to output the substring, having number of groups and word length information at hand. s = input("Type the message: ") if len(s) == 0: exit() print(s) # for Code Playground try: word_length = int(input("Word length: ")) finally: exit() print(word_length) # for Code Playground # replace space with empty string ss = s.replace(" ", "") slen = len(ss) # group by <word_length> characters groups = slen // word_length for i in range(groups): pos = i * word_length print(ss[pos : pos + word_length], end = "-" if i < groups - 1 else "\n") if slen % word_length != 0: print("-", ss[groups * word_length : ], sep = "") print() (Edited)
25th Nov 2019, 10:53 AM
Ipang
0
Ipang Without regex: def myfunc(mystring, myint): return "-".join(mystring[::myint])
23rd Jan 2022, 9:29 AM
Œ ㅤ
Œ ㅤ - avatar