Python中的字符串连接与逗号

1 投票
5 回答
25673 浏览
提问于 2025-04-16 09:04

我在弄清楚Python中的基本数据类型是怎么相互作用的,遇到了一些困难。现在,我想把歌词的不同部分拼接成一个长字符串,然后输出。

当我尝试运行这个脚本时,出现了这个错误:

TypeError: 不能将'str'和'tuple'对象连接在一起。

我把所有不是字符串的东西都放进了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)

5 个回答

3

逗号运算符可以用来创建一个元组。在这一行 "Lyrics += ..." 的右边其实是在创建一个元组。

在Python中,连接字符串可以使用 "+" 这个符号。

Lyrics += str(BottlesOfBeer) + " bottles of beer..." + ...

不过,这种方式并不是最推荐的做法,但对于学习字符串连接来说是可以的。

6

不要用字符串拼接来处理这个问题。把字符串放在一个列表里,最后再把这个列表合并起来。我还建议使用 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” 这个说法在语法上是不正确的。你可能需要创建一个函数,根据数字来给出正确的“bottle”形式。如果涉及到国际化(虽然我知道这可能不是问题),那么你还需要知道 有些语言的形式比“单数”和“复数”更多。

4

Lyrics +=左边的用逗号分隔的列表是在定义一个“元组”。

你需要把逗号改成加号,因为字符串连接不支持用逗号分隔的值。

另外,可以考虑先把要连接的字符串放到一个列表里,然后再用“join”方法来连接它们。

撰写回答