0

I need to display a string on multiple lines at a set interval. For example

if the string is ABCDEFGHI and the interval is 3 then it needs to print

ABC
DEF
GHI

Right now, I have a function with 2 inputs

def show_string(chars: str, interval: int) -> str:
    ...

Please help!

bumblebee
  • 1,811
  • 12
  • 19
  • Does this answer your question? [What's the best way to split a string into fixed length chunks and work with them in Python?](https://stackoverflow.com/questions/18854620/whats-the-best-way-to-split-a-string-into-fixed-length-chunks-and-work-with-the) – fixatd May 14 '20 at 05:35
  • What if the interval is 2 or 4? Whats the output in that case? – Shubham Sharma May 14 '20 at 05:38

7 Answers7

1

Use list comprehension :

def show_string(chars: str, interval: int):
    [print(chars[obj:obj+interval]) for obj in range(0, len(chars), interval)]
Abhishek Kulkarni
  • 1,747
  • 1
  • 6
  • 8
0

You can use the inbuilt function wrap from the textwrap module

from textwrap import wrap

def show_string(chars: str, interval: int):
    words = wrap(chars, interval)
    # Print the words
    for word in words:
        print(word)
    # Or return the list of words
    return words  # contains ['ABC', 'DEF', 'GHI']
bumblebee
  • 1,811
  • 12
  • 19
0

see this simple code:

test="abcdefghi"
x=[]
while len(test) != 0:
    x.append(test[:3])
    test=test[3:]

print(x)
print(''.join(x))
Taher Fattahi
  • 951
  • 1
  • 6
  • 14
0

You can try this, I have used while loop:

def foo(chars,intervals):
    i = 0
    while i < len(chars):
        print(chars[i:i+3])
        i+=3
foo("ABCDEFGHI",3)
JenilDave
  • 606
  • 6
  • 14
0

You can try this probably a more pythonic way than the previous answer, however this function only returns None, because it just prints the values

def show_string(chars: str, interval: int) -> None:

    [print(chars[i:i+interval]) for i in range(0, len(chars), interval)]

if you were to return a list of strings you cans simply rewrite:

def show_string(chars: str, interval: int)-> list[str]:

    return [chars[i:i+interval] for i in range(0, len(chars), interval)]
bertharry
  • 155
  • 1
  • 1
  • 7
0

I think something like this would help.

def show_string(chars: str, interval: int):
    for i in range(0, len(chars), interval):
        print(chars[i:i+interval]) 
Aashutosh Rathi
  • 763
  • 2
  • 13
  • 28
0
from itertools import zip_longest 


def show_string(chars, interval):
    out_string = [''.join(lis) for lis in group(interval, chars, '')] 
    for a in out_string: 
        print(a)

# Group function using zip_longest to split 
def group(n, iterable, fillvalue=None): 
    args = [iter(iterable)] * n 
    return zip_longest(fillvalue=fillvalue, *args) 

show_string("ABCDEFGHI", 3)

Output:

ABC
DEF
GHI
Chirag Maliwal
  • 442
  • 11
  • 25