如何将字符串格式化为形状?

时间:2017-02-09 23:45:34

标签: python formatting shapes

我希望能够打印一个字符串并将其格式化为一个形状。在这里的代码中,它格式化为一个直角三角形,但我也想做其他形状。问题是我不能让字符串在每一行截断并继续,它只是循环在第一个字符。

这就是它的样子

hhhhhhhhhhhhhhh
hhhhhhhhhhhhh
hhhhhhhhhhh
hhhhhhhhh
hhhhhhh
hhhhh
hhh
h

但我希望它看起来像这样

hellowor
ldhowar
eyout
oday
?

我最近一直在努力绕过这个概念,我似乎无法在函数内循环函数。我想我可能错过了索引或循环的一些关键部分,这些都阻止了我。但如果你能告诉我这里,我可能会更多地了解它。我试过谷歌搜索这个问题无济于事。我感谢任何帮助。

到目前为止,这是我的代码:

text = ('hello world how are you today?')

def word():
    for c in text:
        return c

def triangle(i, t = 0):
    if i == 0:
        return 0
    else:
        print '' * (t + 1) + word() * (i * 2 - 1)
        return triangle (i - 1, t + 1)
triangle (8)

编辑:

我添加的另一件事是:

def triangle(i, t = 0):
if i == 0:
    return 0
else:
    for c in text:
        print '' * (t + 1) + word() * (i * 2 - 1)

    return triangle (i - 1, t + 1)

但它会产生同样的问题,因为它只打印“文本”中的第一个字母。

如何遍历每个字母?

1 个答案:

答案 0 :(得分:0)

感谢。基本的答案是你让这个太复杂了。从您的初始行开始在字符串的前面;将余数传递给递归调用。不要费心从字符串中取出单个字符:只需抓住你需要的子集。

请注意,这有两个基本情况:大小命中0,或者您之前没有消息。

def triangle(message, size):
    # Size = 0: we're done; ran out of rows
    if size == 0:
        return
    # Not enough message left: print it all
    if size >= len(message):
        print message
    # print "size" characters and go to next line
    else:
        print message[:size]
        triangle(message[size:], size-1)


text = "hello world how are you today?"
triangle(text, 8)
print ""
triangle(text, 7)

输出:

hello wo
rld how
 are y
ou to
day?

hello w
orld h
ow ar
e yo
u t
od
a

STRING SLICES

一般表格是

str[start : end : step]

这将从str [start]到str [end-1]包含子串。如果省略任何参数,则默认值为

start = 0
end = -1 (through the end of the string)
step = 1

由于我们很少会经常浏览字符串,因此步骤参数几乎总是默认为1.

相关问题