简体   繁体   中英

Print a string on multiple lines

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!

Use list comprehension:

def show_string(chars: str, interval: int):
    [print(chars[obj:obj+interval]) for obj in range(0, len(chars), interval)]

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

see this simple code:

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

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

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)

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM