我正在创建一个python脚本,可打印出“99瓶啤酒”的整首歌,但相反。我唯一不能逆转的是数字,它们是整数,而不是字符串。
这是我的完整剧本,
def reverse(str):
return str[::-1]
def plural(word, b):
if b != 1:
return word + 's'
else:
return word
def line(b, ending):
print b or reverse('No more'), plural(reverse('bottle'), b), reverse(ending)
for i in range(99, 0, -1):
line(i, "of beer on the wall")
line(i, "of beer"
print reverse("Take one down, pass it around")
line(i-1, "of beer on the wall \n")
我知道我的反向函数将字符串作为参数,但是我不知道如何接受整数,或者稍后如何在脚本中反转整数。
最佳答案
您正在以一种非常奇怪的方式来处理这个问题。您已经具有反转功能,那么为什么不让line
只是以正常方式构建线呢?
def line(bottles, ending):
return "{0} {1} {2}".format(bottles,
plural("bottle", bottles),
ending)
运行方式如下:
>>> line(49, "of beer on the wall")
'49 bottles of beer on the wall'
然后将结果传递给
reverse
:>>> reverse(line(49, "of beer on the wall"))
'llaw eht no reeb fo selttob 94'
这使得分别测试代码的各个部分以及将它们放在一起时看到的情况变得更加容易。
关于python - 如何在python中反转int?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/24953303/