<p>是的,我知道这个小问题很糟糕,但我正在尝试Python,我想它会很简单。我很难搞清楚本地数据类型在Python中是如何交互的。在这里,我试图将<a href="http://99-bottles-of-beer.net/lyrics.html" rel="nofollow">lyrics</a>的不同部分连接成一个长字符串,该字符串将作为输出返回。</p>
<p>尝试运行脚本时收到的错误是“type error:无法连接'str'和'tuple'对象”。我将所有不是字符串的内容都放在函数str()中,但显然有些内容仍然是“tuple”(以前从未使用过的数据类型)。</p>
<p>有人能告诉我如何将其中的元组转换成一个字符串,这样就可以顺利地连接起来吗?</p>
<p>(p.S.我使用变量“Copy”,因为我不确定当我减少另一个变量时,它是否会破坏for循环构造。会吗?)</p>
<pre><code>#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)
</code></pre>
<p>有些人建议建立一个列表并加入它。我编辑了一点,我认为这是你们的意思,但你能告诉我这是不是首选的方法?</p>
<pre><code>#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)
</code></pre>