简体   繁体   English

Python - 创建一棵圣诞树

[英]Python - create a Christmas Tree

Trying to print a Christmas tree using a sentence.尝试使用句子打印圣诞树。 Below is my code which does not quite work.下面是我的代码,它不太工作。

sentence = 'The whole Christmas tree.'
for word in sentence.split():
    for i, char in enumerate(word, 1): # Avoid a separate counter
        print(9 * " ", 2 * char * i)

desired output:所需的 output:

        TT
       hhhh
      eeeeee
        ww
       hhhh
      oooooo
     llllllll
    eeeeeeeeee
        CC
       hhhh
      rrrrrr
     iiiiiiii
    ssssssssss
   tttttttttttt
  mmmmmmmmmmmmmm
 aaaaaaaaaaaaaaaa
ssssssssssssssssss
        tt
       rrrr
      eeeeee
     eeeeeeee
    ..........

You're close.你很近。 First you're printing a tuple.首先你要打印一个元组。 Instead you want to concatenate the strings of spaces and characters and print the resulting string.相反,您想要连接空格和字符的字符串并打印结果字符串。 Second, you're printing a constant number of leading spaces in each line.其次,您在每行中打印恒定数量的前导空格。 The number should vary by line.数字应因行而异。 If you examine the desired output, you'll see that the number of characters to the center of the tree always needs to be equal to the length of the longest word.如果您检查所需的 output,您会发现到树中心的字符数始终需要等于最长单词的长度。 You want to starting printing non-space characters after emitting a number of spaces such that they plus half the non-space characters get to the center line.您希望在发出多个空格后开始打印非空格字符,这样它们加上一半的非空格字符到达中心线。

Coding these ideas in a way as close as possible to what you already have,以尽可能接近您已有的方式对这些想法进行编码,

sentence = 'The whole Christmas tree.'
words = sentence.split()
center = max(len(w) for w in words)
for word in words:
    for i, char in enumerate(word, 1):
        print(' ' * (center - i) + 2 * char * i)

This will work fine with any sentence.这适用于任何句子。

One thing that you are clearly missing here is proper offset.您在这里显然缺少的一件事是适当的偏移。 The longest row in the whole tree will be the one from 's' in 'Christmas'.整棵树中最长的一排将是“圣诞节”中“s”中的那一排。 It will be 18 characters long.它将有 18 个字符长。 To create an equal offset you want to exactly add (18 - lengthOfRow)//2 empty spaces.要创建相等的偏移量,您需要精确添加(18 - lengthOfRow)//2空格。 Take a look at the code below:看看下面的代码:

sentence = 'The whole Christmas tree.'
for word in sentence.split():
    for i in range(len(word)):
        # For each word letter
        letters = word[i] * 2 * (i+1)
        # Add equal offset
        offset = " " * ((18 - len(letters)) // 2)
        print(offset + letters)

It produces:它产生:

        TT
       hhhh
      eeeeee
        ww
       hhhh
      oooooo
     llllllll
    eeeeeeeeee
        CC
       hhhh
      rrrrrr
     iiiiiiii
    ssssssssss
   tttttttttttt
  mmmmmmmmmmmmmm
 aaaaaaaaaaaaaaaa
ssssssssssssssssss
        tt
       rrrr
      eeeeee
     eeeeeeee
    ..........

This magic 18 used there is the length of the longest word in the sentence, multiplied by a factor of 2. If you would like to change the sentence, you can find the right number in this way:这里使用的这个魔法 18 是句子中最长单词的长度,乘以 2。如果你想改变句子,你可以这样找到正确的数字:

offset = 2 * len(sorted(sentence.split(), key=len)[-1])

Format String Syntax with '>' to force the field to be right-aligned使用'>'格式化字符串语法以强制字段右对齐

For python <=3.5对于 python <=3.5

print('{0: >9}{1}'.format(char * i, char * i))

For python >3.5对于 python >3.5

print(f'{char * i: >9}{char * i}')
print(9 * " ", 2 * char * i)

What is the purpose of initial "9" here?这里首字母“9”的目的是什么? It is just adding a padding may be you need it, if not get rid of it.它只是添加一个填充可能是你需要的,如果没有摆脱它。

I would assume the first argument to print to be same the center position of the tree "minus" the loop couter which is i.我假设要打印的第一个参数与树的中心 position “减去”循环计数器 i 相同。 So may be something like this will work:所以可能这样的事情会起作用:

print((x - i) * " ", 2 * char * i)

Where x is:其中 x 是:

len(sentence) / 2

You can also try this solution which uses python's string formatting, so you don't need to worry about the offset.你也可以试试这个使用python字符串格式的解决方案,所以你不需要担心偏移量。

To learn more about string formatting, you can read this .要了解有关字符串格式的更多信息,您可以阅读.

sentence = 'The whole Christmas tree.'

word = []
for item in sentence:
    if ' ' not in item:
        word.append(item)
    else:
        for ind, inner in enumerate(word):
            print('{:^20}'.format(''.join([inner for _ in range(2 * (ind + 1))])))
        word = []

I noticed this part of the code print(9 * " ", 2 * char * i) .我注意到这部分代码print(9 * " ", 2 * char * i) This will cause you to only print half of your christmas tree.这将导致您只打印一半的圣诞树。

You can replace that with this: print(((len(sentence) // 2) - i) * " ", 2 * char * i)您可以将其替换为: print(((len(sentence) // 2) - i) * " ", 2 * char * i)

This will get you the desired output you want这将为您提供所需的 output

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM