为Python打印带有字母“ abcdefghi”的“ W”模式

时间:2018-10-11 17:57:29

标签: python

我想问一个有关通过字母打印“ W”图案的问题,这是我的代码,但是我得到了这样的输出

def stringing(sentence,start):    
    if start == 'T':
        j = 0

        for row in range(3):
            for col in range(9):
                if col-row == 0 or row+col == 0 or row+col == 4 or col+row == 8 or col-row == 4:
                    print(sentence[j], end='')
                    j += 1
                else:
                    print(end=" ") 
            print()  

stringing('abcdefghi', 'T')

a   b   c
 d e f g 
  h   i 

有人可以在这件事上协助我吗?我想这样输出

a   e   i
 b d f h
  c   g

非常感谢!

2 个答案:

答案 0 :(得分:3)

我决定尝试一下。有点棘手,但还不错。这就是我想出的。经过测试并为我工作,甚至适用于较大或较短的琴弦。

def stringing(sentence,start):    
    if start == 'T':

        offset1 = '   '
        offset2 = ' '
        str1 = ''
        str2 = ' '
        str3 = '  '

        str_number = 1
        for letter in sentence:

            if str_number % 4 == 1:
                str1 += letter+offset1

            if str_number % 2 == 0:
                str2 += letter+offset2              

            if str_number % 4 == 3:
                str3 += letter+offset1

            str_number+=1

        print(str1)
        print(str2)
        print(str3)


stringing('abcdefghi', 'T')

答案 1 :(得分:1)

请参考此链接以获取答案:Wave Strings

这是从网站复制的代码。我做了一些小的更改,以使其与您发布的代码相关联,但是无论如何,我希望这会有所帮助!

# Function that takes string 
# and zigzag offset 
def stringing(s, n): 

    # if offset is 1 
    if (n == 1): 

        # simply print the 
        # string and return 
        print(s)              
        return

    # Get length of the string 
    l = len(s) 

    # Create a 2d character array 
    a = [[" " for x in range(l)] for y in range(l)]  

    # for counting the  
    # rows of the ZigZag 
    row = 0
    for i in range(l): 

        # put characters in the matrix 
        a[row][i] = s[i];  

        # You have reached the bottom 
        if row == n - 1: 
            down = False    
        elif row == 0: 
            down = True
        if down == True: 
            row = row + 1
        else: 
            row = row - 1

    # Print the Zig-Zag String 
    for i in range(n): 
        for j in range(l): 
            print(str(a[i][j]), end = " ") 
        print() 

# Driver Code 
s = "abcdefghi"
n = 3 #represents the number of rows you want the wave to be
stringing(s, n) 

# This code is contributed  
# by ChitraNayal 

输出结果应如下所示:

a       e       i 
  b   d   f   h   
    c       g