【问题标题】:Stretching a string to number of characters [Python]将字符串拉伸到字符数 [Python]
【发布时间】:2020-05-15 11:03:46
【问题描述】:

假设有一个看起来像这样的列表/字符串 - a = 'erik ffffffffff f f f f f '。 通过b = a.split(),我可以获得包含特定“单词”的列表。此列表中的字符总数为sum([len(i) for i in b]),即19。

现在,我非常坚持有效地想出一种方法来拉伸这个列表,以便通过在单词之间插入空格来将结果字符串“对齐”到一定的宽度。假设所需的宽度是 30。那么结果应该类似于c = 'erik ffffffffff f f f f f',只是一个与数字字符(宽度)对齐的字符串,例如在 Word 中。

我的想法是这样的(不工作):

a = 'erik ffffffffff f f f f f '
width = 30
b = a.split()
c = b.copy()
print(b)

spaces = width - sum([len(i) for i in b])
for i, item in cycle(enumerate(c)):
    print(i, item)
    if spaces == 0:
        break
    c[i] = item + ' '
    spaces -= 1
    print(spaces)

print(c)
sum([len(i) for i in c])

【问题讨论】:

标签: python string list


【解决方案1】:

您可以让我们使用string.replace 可选参数count,它替换了前x 个出现次数(最多!)。这就是为什么你将它循环到while 并重新计算差异,直到你达到所需的宽度。这是一个例子。

a = 'erik ffffffffff f f f f f '
width = 50

b=a.strip()  #remove leading and trailing whitespace
diff=width-len(b)
while diff > 0:
    b=b.replace(' ','  ',diff)
    diff = width - len(b)

print(b)
print(len(b))

输出:

erik        ffffffffff       f    f    f    f    f
50

【讨论】:

  • 谢谢!这看起来像一个更有效的解决方案。但是,我还需要字符串以一个单词结尾,而不是空格。 (它还没有包含在我的代码中)。
  • 好的,我需要多思考一下。第一个字符串上的简单 strip() 就可以完成这项工作。
  • 不知何故,当行短于 20 个字符时,此解决方案不再适用于我。它卡在while循环中。您认为问题可能出在哪里?
【解决方案2】:

或者如果您不希望间距相差一个以上:

a = 'erik ffffffffff f f f f f '
width = 35

def stretch(line, width):
    line = line.strip()
    if " " in line:
        diff = width - len(line)
        gap = " "
        while diff > 0:
            line = line.replace(gap, gap+" ", diff)
            diff = width - len(line)
            gap += " "
    return line

print(stretch(a, width))

输出:

erik   ffffffffff   f   f   f  f  f

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-11
    • 2019-02-13
    • 2011-01-18
    • 2018-02-01
    • 2012-01-12
    相关资源
    最近更新 更多