Skip to main content
 首页 » 编程设计

python之Python 中的字符串连接和逗号

2025年05月04日21leader

我很难搞清楚原生数据类型在 Python 中是如何交互的。在这里,我试图连接 the lyrics 的不同部分成一个长字符串,将作为输出返回。

我在尝试运行脚本时收到的错误是:

TypeError: cannot concatenate 'str' and 'tuple' objects.

我把所有不是字符串的东西都放在函数 str() 中,但显然有些东西仍然是“元组”(我以前从未使用过的数据类型)。

我怎样才能将其中的任何元组转换成一个字符串,以便所有元组顺利连接起来?

(附言:我使用了变量“Copy”,因为我不确定当我递减另一个变量时,它是否会扰乱 for 循环结构。会吗?)

#99 bottles of beer on the wall lyrics 
 
def BottlesOfBeerLyrics(NumOfBottlesOfBeer = 99): 
        BottlesOfBeer = NumOfBottlesOfBeer 
        Copy = BottlesOfBeer 
        Lyrics = '' 
 
        for i in range(Copy): 
                Lyrics += BottlesOfBeer, " bottles of beer on the wall, ", str(BottlesOfBeer), " bottles of beer. \n", \ 
                "Take one down and pass it around, ", str(BottlesOfBeer - 1), " bottles of beer on the wall. \n" 
 
                if (BottlesOfBeer > 1): 
                        Lyrics += "\n" 
 
                BottlesOfBeer -= 1 
 
        return Lyrics 
 
print BottlesOfBeerLyrics(99) 

有些人建议建立一个列表并加入其中。我对其进行了一些编辑,但这是首选方法吗?

#99 bottles of beer on the wall lyrics - list method 
 
def BottlesOfBeerLyrics(NumOfBottlesOfBeer = 99): 
        BottlesOfBeer = NumOfBottlesOfBeer 
        Copy = BottlesOfBeer 
        Lyrics = [] 
 
        for i in range(Copy): 
                Lyrics += str(BottlesOfBeer) + " bottles of beer on the wall, " + str(BottlesOfBeer) + " bottles of beer. \n" + \ 
                "Take one down and pass it around, " + str(BottlesOfBeer - 1) + " bottles of beer on the wall. \n" 
 
                if (BottlesOfBeer > 1): 
                        Lyrics += "\n" 
 
                BottlesOfBeer -= 1 
 
        return "".join(Lyrics) 
 
print BottlesOfBeerLyrics(99) 

请您参考如下方法:

不要为此使用字符串连接。将字符串放入列表中,并在末尾加入列表。我还建议使用 str.format。

verse = "{0} bottles of beer on the wall, {0} bottles of beer.\n" \ 
        "Take one down and pass it around, {1} bottles of beer on the wall.\n" 
 
def bottles_of_beer_lyrics(bottles=99): 
    lyrics = [] 
    for x in range(bottles, 0, -1): 
        lyrics.append(verse.format(x, x-1)) 
    return '\n'.join(lyrics) 

您还可以使用生成器表达式更直接地获得结果:

def bottles_of_beer_lyrics(bottles=99): 
    return '\n'.join(verse.format(x, x-1) for x in range(bottles, 0, -1)) 

最后一点,您应该注意“1 bottles”在语法上是不正确的。您可能想要创建一个函数,它可以根据数字为您提供正确形式的“瓶子”。如果国际化是一个问题(我知道它可能不是)那么你也应该知道 some languages有比“单数”和“复数”更多的形式。