简体   繁体   English

Python:如何打印出一定范围的字母

[英]Python: How to print out a certain range of the alphabet

I'm trying to make a Battleship grid, with numbers on the left and the letters on top. 我正在尝试制作一个战舰网格,左侧是数字,顶部是字母。 I'm confused on how you would print out a certain amount of letters and add them on with python. 我对如何打印出一定数量的字母并将其添加到python上感到困惑。 I'm an extremely new beginner when it comes to Python. 关于Python,我是一个非常新的初学者。

For example: 例如:

    def displayGrid(Rows,Columns):
        output = '| '
        for title in range(97,110):
            output = output + chr(title)
            output = output + ' |'
        print(output)

        for row in range(Rows):
            output = str(row + 1) + '| '
            for col in range(Columns):
                output = output + " | "
            print(output)

    Rows = int(input("Number of rows you want? \n"))
    Columns = int(input("Number of columns you want? \n"))

    displayGrid(Rows, Columns)

I want it so the number of Columns is the number of letters that it prints out but I can't seem to figure it out. 我想要它,所以“列数”是它打印出来的字母数,但我似乎无法弄清楚。

Your first loop ( for title in range(97,110): ) will always have a fixed length (of 110-97=13 elements), so you'll always end up with the same first line, regardless of how many columns you want. 您的第一个循环( for title in range(97,110): )将始终具有固定的长度(110-97 = 13个元素),因此,无论您想要多少列,都将始终以相同的第一行结尾。

Try something like for title in range(97, 97+Columns): 尝试类似for title in range(97, 97+Columns):

replace this 取代这个

    for title in range(97,110):
        output = output + chr(title)
        output = output + ' |'
    print(output)

by 通过

output = " |" +"|".join([chr(i) for i in range(97,97+Columns)])
print(output)

You can access the lowercase letters through 您可以通过以下方式访问小写字母

from string import lowercase

And a clean way to achieve your string would be: 实现字符串的一种干净方法是:

result = "| " + " | ".join(lowercase[0:size]) + " |"

Few tips - 一些提示-

  1. When you have an iteratable you want to print and join with certain delimiter you can use join - '|'.join(["a", "b", "c"]) a|b|c 当您有一个可迭代的对象时,要打印并使用某些定界符进行连接,可以使用join- '|'.join(["a", "b", "c"]) a|b|c

  2. from string import lowercase will give you a string (which you can iterate on) all the lower case letters. from string import lowercase将为您提供一个字符串(您可以对其进行迭代)所有小写字母。

  3. Check python itertools - https://docs.python.org/2/library/itertools.html 检查python itertools- https: //docs.python.org/2/library/itertools.html

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

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