+ 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`.
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)
+ 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))
+ 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)
0
Ipang Without regex:
def myfunc(mystring, myint):
return "-".join(mystring[::myint])