Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/323.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 我想在给定列数的情况下,以矩阵形式打印每个单词中的字母_Python_String_Matrix - Fatal编程技术网

Python 我想在给定列数的情况下,以矩阵形式打印每个单词中的字母

Python 我想在给定列数的情况下,以矩阵形式打印每个单词中的字母,python,string,matrix,Python,String,Matrix,我有一个字符串thestackoverflow 我还有#columns=4 然后我希望输出为 thes tack over flow 您可以查看textwrap import textwrap string = 'thestackoverflow' max_width = 4 result = textwrap.fill(string,max_width) print(result) 如果您不想使用任何模块 string = 'thestackoverflow' max_widt

我有一个字符串
thestackoverflow
我还有#columns=4
然后我希望输出为

thes  
tack  
over  
flow

您可以查看
textwrap

import textwrap
string = 'thestackoverflow'
max_width = 4
result = textwrap.fill(string,max_width)
print(result)
如果您不想使用任何模块

string = 'thestackoverflow'
max_width = 4
row = 0
result = ''
while row*max_width < len(string):
    result+='\n'+string[row*max_width:(row+1)*max_width]
    row+=1
result = result.strip()
print(result)
string='thestackoverflow'
最大宽度=4
行=0
结果=“”
行*最大宽度<长度(字符串):
结果+='\n'+字符串[行*最大宽度:(行+1)*最大宽度]
行+=1
result=result.strip()
打印(结果)

您可以使用python切片表示法来完成此操作。
有关切片表示法的详细说明,请参阅此线程:

问题的示例代码:

>>> input_string = "thestackoverflow"
>>> chop_size = 4
>>> while(input_string):
...  print input_string[:chop_size]
...  input_string = input_string[chop_size:]
...
thes
tack
over
flow

不要添加标签
设计模式
在将标签添加到帖子之前,请查看标签说明
>>> input_string = "thestackoverflow"
>>> chop_size = 4
>>> while(input_string):
...  print input_string[:chop_size]
...  input_string = input_string[chop_size:]
...
thes
tack
over
flow