【问题标题】:Write a test program that prints ten characters per line from 1 to Z编写一个测试程序,每行打印从 1 到 Z 的十个字符
【发布时间】:2017-07-17 16:52:48
【问题描述】:

编写一个使用以下标头打印字符的函数:
def printChars(ch1, ch2, numberPerLine):
此函数打印ch1ch2 之间的字符,每行带有指定的数字。
我想编写一个测试程序,从 1 到 Z 每行打印十个字符。

def main():
    printCenter code herehars("1","Z",10)

def printChars(ch1,ch2,numberPerLine):
    for i in range(ord(ch1), ord(ch2) + 1):
        print(chr(i), end='')
        if (i - ord(ch1)) % numberPerLine == numberPerLine - 1:
            print()

main()

输出:

123456789:
;<=>?@ABCD
EFGHIJKLMN
OPQRSTUVWX
YZ

程序应该打印:

0123456789
ABCDEFGHIJ
KLMNOPQRST
UVWXYZ

【问题讨论】:

标签: python function


【解决方案1】:

你可以试试这个,

>>> import string
>>> alpha_caps = string.digits+string.ascii_uppercase
>>> alpha_caps_res = ' '.join(alpha_caps[i:i+10] for i in range(0, len(alpha_caps), 10))
>>> alpha_caps_res
'0123456789 ABCDEFGHIJ KLMNOPQRST UVWXYZ'

【讨论】:

    【解决方案2】:

    一种方法是首先构建可用的输出chars,手动创建字符串或从string.digits 获取值。接下来使用字符串索引来确定您的ch1ch2 字符在字符串中的位置。有了这个,您就可以对字符串进行切片以提供您需要的所有字符。最后使用range()0output 的长度。最后一个参数告诉它跳过numberPerLine 值。然后,这将为您提供打印的每一行的起始索引。

    import string
    
    def printChars(ch1, ch2, numberPerLine):
        chars = string.digits + string.ascii_uppercase  # Same as doing 0123456789A......Z
        output = chars[chars.index(ch1):chars.index(ch2)+1]
    
        for start in range(0, len(output), numberPerLine):
            print(output[start:start+numberPerLine])
    
    printChars("0", "Z", 10)
    

    给你:

    0123456789
    ABCDEFGHIJ
    KLMNOPQRST
    UVWXYZ
    

    【讨论】:

      【解决方案3】:

      您可能正在寻找这样的东西:

      def main():
          printCenter code herehars("1","Z",10)
      
      def printChars(ch1,ch2,numberPerLine):
          counter = 0
          for i in range(ord(ch1), ord(ch2) + 1):
              if chr(i).isalnum():
                  print(chr(i), end='')
                  counter++
              if counter % numberPerLine == numberPerLine - 1:
                  print()
      
      main()
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-04-12
        • 1970-01-01
        • 2018-09-18
        • 1970-01-01
        • 1970-01-01
        • 2022-10-24
        • 2016-10-16
        相关资源
        最近更新 更多