在Python中只打印一定数量的字符

时间:2013-01-16 01:02:27

标签: python string

  

可能重复:
  Iterate an iterator by chunks (of n) in Python?

假设我有一个492个字符的字符串存储在一个变量中。如何打印前50个字符,然后转到下一行,然后打印出下一个50,最后打印一个包含42个字符的行?

4 个答案:

答案 0 :(得分:5)

chars_per_line = 50
for i in range(0, len(s), chars_per_line):
    print s[i:i+chars_per_line]

答案 1 :(得分:2)

for line in mystring.splitlines():
    print line[:50]

答案 2 :(得分:0)

In [363]: mystr = "A"*492

In [364]: print '\n'.join(mystr[i*width:(i+1)*width] for i in range(int(math.ceil(float(len(mystr))/width))))
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA

答案 3 :(得分:0)

正如@Martijn Pieters暗示的那样,如果你有办法iterate an iterator by chunks (of n),这将是非常容易的。如果您阅读了该问题,那么就可以做到这一点。

所以,鉴于来自itertools recipesgrouper实施(或您偏好其他问题的其他任何内容):

lines = [''.join(group) for group in grouper(50, my_string, '')]

或者,如果您只想将它​​们打印出来:

for group in grouper(50, my_string, ''):
    print ''.join(group)

一旦你知道grouper存在,我认为这比Joel Cornett的回答简单。请注意,他在第一个版本中没有工作,必须修复;这个几乎不可能出错。任何消除fencepost错误可能性的东西通常都会更好;这就是为什么我们有for - in循环和enumerate而不是C风格的for循环,等等。

这是在行动:

>>> my_string='1234567890'*49+'12'
>>> print my_string
123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012
>>> # That was ugly…
>>> for group in grouper(50, my_string, ''):
...     print ''.join(group)
12345678901234567890123456789012345678901234567890
12345678901234567890123456789012345678901234567890
12345678901234567890123456789012345678901234567890
12345678901234567890123456789012345678901234567890
12345678901234567890123456789012345678901234567890
12345678901234567890123456789012345678901234567890
12345678901234567890123456789012345678901234567890
12345678901234567890123456789012345678901234567890
12345678901234567890123456789012345678901234567890
123456789012345678901234567890123456789012
>>> # Pretty!