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!

2

7 Answers 7

1

Use list comprehension :

def show_string(chars: str, interval: int):
    [print(chars[obj:obj+interval]) for obj in range(0, len(chars), interval)]
Sign up to request clarification or add additional context in comments.

Comments

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']

Comments

0

see this simple code:

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

print(x)
print(''.join(x))

Comments

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)

Comments

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)]

Comments

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]) 

Comments

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.