Python中的字符串连接

jke*_*eys 1 python string tuples

是的,我知道这个小问题非常蹩脚,但我正在尝试Python,我认为它很简单.我很难搞清楚本机数据类型在Python中的交互方式.在这里,我试图将歌词的不同部分连接成一个长字符串,它将作为输出返回.

我在尝试运行脚本时收到的错误是"TypeError:无法连接'str'和'tuple'对象." 我在函数str()中放入了不是字符串的所有东西,但显然某些东西仍然是"元组"(我之前从未使用过的数据类型).

有人可以告诉我如何获取字符串中的任何元组所以这将顺利连接吗?

(PS我使用了变量"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)
Run Code Online (Sandbox Code Playgroud)

有些人建议建立一个列表并加入它.我编辑了一下我认为你们的意思,但你能否告诉我这是否是首选方法?

#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)
Run Code Online (Sandbox Code Playgroud)

Mar*_*ers 5

不要为此使用字符串连接.将字符串放在列表中并在结尾处加入列表.我也建议使用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)
Run Code Online (Sandbox Code Playgroud)

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

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

最后一点,你应该注意"1瓶"在语法上是不正确的.您可能想要创建一个函数,根据数字可以为您提供正确的"瓶子"形式.如果国际化是一个问题(我知道它可能不是),那么你也应该意识到某些语言的形式多于"单数"和"复数".