【问题标题】:Adding the letters of the alphabet to the string in order将字母表中的字母按顺序添加到字符串中
【发布时间】:2021-10-31 21:36:44
【问题描述】:

我有一个字母表,例如:ABCDEFGHILJKLMN

我有一个类似的字符串:https://test.com/c={here}

我想将上面的字母分别添加到这个字符串的末尾,这里说的地方。

例子:

我写了这样的代码:

class GetNames():
    def __init__(self):
        self.url = "https://test.com/c="
        self.new_url = []
        self.letters = ['A','B','C','Ç','D','E','F','G','H','I','İ','J','K','L','M','N','O',
                        'Ö','P','R','S','T','Ş','U','Ü','V','Y','Z']

    def get_letter(self):
        index = 0
        while self.letters:
            self.url += self.letters[index]
            self.new_url.append(self.url)
            index += 1
            if index == 28:
                break

        print(self.new_url)

我得到这样的输出:

我该如何解决这个问题?

【问题讨论】:

    标签: arrays python-3.x string list char


    【解决方案1】:

    插入这一行添加第一个while循环,如下所示:

    self.url = "https://test.com/c="
    

    最后代码:

    class GetNames():
        def __init__(self):
            self.url = "https://test.com/c="
            self.new_url = []
            self.letters = ['A','B','C','Ç','D','E','F','G','H','I','İ','J','K','L','M','N','O',
                            'Ö','P','R','S','T','Ş','U','Ü','V','Y','Z']
    
        def get_letter(self):
            index = 0
            while self.letters:
                self.url = "https://test.com/c="
                self.url += self.letters[index]
                self.new_url.append(self.url)
                index += 1
                if index == 28:
                    break
    
            print(self.new_url)
    

    输出:

    ['https://test.com/c=A', 'https://test.com/c=B', 'https://test.com/c=C', ...
    

    【讨论】:

      【解决方案2】:

      在 self.url += self.letters[index] 之后 self.new_url.append(self.url)

      确保添加这一行:self.url="https://test.com/c="

      【讨论】:

        【解决方案3】:

        您的代码看起来很复杂,您可以使用 for 循环而不是 while

        class GetNames:
            def __init__(self):
                self.url = 'http://test.com/c='
                self.new_url = []
                self.letters = ['A','B','C','Ç','D','E','F','G','H','I','İ','J','K','L','M','N','O',
                                'Ö','P','R','S','T','Ş','U','Ü','V','Y','Z']
        
            def get_letter(self):
                for i in range(28):
                    self.new_url.append(self.url + self.letters[i])
        
        a = GetNames()
        a.get_letter()
        print(a.new_url)
        

        输出

        ['http://test.com/c=A', 'http://test.com/c=B', ... , 'http://test.com/c=Y', 'http://test.com/c=Z']
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2014-06-13
          • 2015-05-07
          • 1970-01-01
          • 1970-01-01
          • 2017-10-04
          • 2014-11-26
          • 1970-01-01
          • 2022-07-29
          相关资源
          最近更新 更多