x python中的字符串长度

时间:2013-10-19 19:59:46

标签: python string

您好,我想创建一个像这样工作的应用程序: 来自文件的字符串,例如:

AAAAa aaaaa
bb bbbbbbbbbbbbb
ccccccccccccc
当x将是行的最大长度时,

将被x包裹,因此对于x = 10,它将看起来像

AAAAa aaaa
aabb bbbbb   
....

我已尝试过此代码,但无法正常工作

def length(x):
    return x
t = open("text.txt", "r")
x = int(input("Enter length: \n"))
length(x)
for line in t:
     print(line.strip())
     if int(len(line) >= length(x)):
          print("\n")
t.close()

此代码正在做其他事情,你能帮帮我吗? :)

3 个答案:

答案 0 :(得分:1)

>>> t='''AAAAa aaaaa
bb bbbbbbbbbbbbb
ccccccccccccc'''
>>> x = int(raw_input("Enter length: "))
>>> print '\n'.join(t.replace('\n', '')[i:i+x] for i in range(0, len(x), x))
AAAAa aaaa
abb bbbbbb
bbbbbbbccc
cccccccccc

这样:

with open("text.txt") as f:
    t = f.read()
x = int(input("Enter length: \n"))
print '\n'.join(t.replace('\n', '')[i:i+x] for i in range(0, len(x), x))
close t

答案 1 :(得分:0)

似乎他们想要获取文本文件并遍历每个字符,直到达到X然后开始一个新行继续打印文本,直到再次到达x。

这需要修改并且未经测试

def textiterator(xinput):
    counter = 0
    transformedtext = ''
    textfromfile = ''
    textfile = open('youroriginaltextfile.txt', 'r')

    for eachline in textfile:
            textfromfile = textfromfile + eachline

    while counter <= len(textfromfile):

        if counter not equal to % of xinput: ##modulus operator needs to be added for multiple of xinput
            transformedtext = transformedtext + textfromfile[counter]
            counter = counter + 1

        else:
            transformedtext = transformedtext + '\n'


    return transformedtext

答案 2 :(得分:0)

这应该这样做:

def in_groups(seq, n):
    # see http://docs.python.org/2/library/itertools.html#recipes
    return zip(*[iter(seq)] * n)

l = int(raw_input("Enter length: "))
with open("text.txt") as f:
    contents = f.read()
print '\n'.join(''.join(t) for t in in_groups(contents.replace('\n', ''), l))