I am trying to split a string into groups of 4 letters. Not into a list in a string. without using import
Example 1:
hello world
Output:
hell owor ld
Example 2:
if you can dream it, you can do it
Output:
ifyo ucan drea mit, youc ando it
I am trying to split a string into groups of 4 letters. Not into a list in a string. without using import
Example 1:
hello world
Output:
hell owor ld
Example 2:
if you can dream it, you can do it
Output:
ifyo ucan drea mit, youc ando it
 
    
    One option would be to strip all whitespace from the input, then use re.findall on the pattern .{1,4} to find all blocks of 4 (or however many available) characters.  Then join that list together by space to generate the final output.
inp = "if you can dream it, you can do it"
parts = re.findall(r'.{1,4}', re.sub(r'\s+', '', inp))
output = ' '.join(parts)
print(output)
This prints:
ifyo ucan drea mit, youc ando it
 
    
    full_word = "hello world, how are you?"
full_word = full_word.replace(" ", "")
output = ""
for i in range(0, len(a)-8, 4):
    output += full_word[i:i + 4]
    output += " "
print(output)
output = hell owor ld,h owar eyou ?
 
    
    here is a solution without the need of importing re:
input_string = "if you can dream it, you can do it"
# The number of characters wanted
chunksize=4
# Without importing re
# Remove spaces
input_string_without_spaces = "".join(input_string.split())
# Result as a list
result_as_list = [input_string_without_spaces[i:i+chunksize] for i in range(0, len(input_string_without_spaces), chunksize)]
# Result as string
result_as_string = " ".join(result_as_list)
print(result_as_string)
Output:
ifyo ucan drea mit, youc ando it
 
    
    Please find my solution below with explanation
string  = "if you can dream it, you can do it"
string = string.replace(' ','') #replace whitespace so all words in string join each other
n = 4 # give space after every n chars
  
out = [(string[i:i+n]) for i in range(0, len(string), n)] # Using list comprehension to adjust each words with 4 characters in a list
  
# Printing output and converting list back to string 
print(' '.join(out)) 
output :
ifyo ucan drea mit, youc ando it
 
    
    pattern = "if you can dream it, you can do it"
i = 0
result = ""
for s in pattern:
    if not s == " ":
        if i == 4:
            i = 0
            result += " "
        result += s
        i += 1
print(result)
output:
ifyo ucan drea mit, youc ando it
