擅长:python、mysql、java
<p>不要对此使用字符串连接。将字符串放入列表中,并在最后加入列表。我还建议使用<code>str.format</code>。</p>
<pre><code>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)
</code></pre>
<p>还可以使用生成器表达式更直接地获得结果:</p>
<pre><code>def bottles_of_beer_lyrics(bottles=99):
return '\n'.join(verse.format(x, x-1) for x in range(bottles, 0, -1))
</code></pre>
<p>最后一点,你应该注意“1瓶”在语法上是不正确的。您可能需要创建一个函数,该函数可以根据数字为您提供正确的“瓶子”形式。如果国际化是一个问题(我知道可能不是),那么您还应该知道<a href="http://en.wikipedia.org/wiki/Plural#Other_languages" rel="nofollow">some languages</a>的形式不仅仅是“单数”和“复数”。</p>