[英]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如果字符串是
ABCDEFGHI
并且间隔是 3 那么它需要打印
ABC
DEF
GHI
Right now, I have a function with 2 inputs现在,我有一个带 2 个输入的 function
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您可以使用
textwrap
模块中的内置 function wrap
行
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:你可以试试这个,我用过while循环:
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您可以尝试这可能比上一个答案更 Pythonic 的方式,但是这个 function 只返回 None,因为它只打印值
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: Output:
ABC
DEF
GHI
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.