为什么不能在切片中使用变量?

时间:2019-05-11 04:24:33

标签: python

因此,我回答了有关编码蝙蝠的一个问题,该问题要求通过定义一个占原始字符串长度一半的变量并使用该变量对字符串进行切片来将n次字符串返回n次。

编码蝙蝠接受了结果,但是当我尝试在Jupyter Notebook上重新创建问题时,它仅接受“整数或None或 index 方法”。

我在做什么错了?

我是Python的初学者,只想确保我正在学习正确的格式。

def first_half(str):
  newword = len(str) / 2
  return '{}'.format(str[:newword])

对于first_half('Milkshakes'),我希望得到'Milk'。 但是,我收到的错误是:

TypeError: slice indices must be integers or None or have an __index__ method

1 个答案:

答案 0 :(得分:2)

这是因为len(str) / 2为您提供了浮点值5.0,并且您不能将float用作字符串slice的参数,无法通过执行int(len(str) / 2)将参数转换为int,从而得到您5,它应该可以工作。请注意,以上内容仅适用于Python 3仍适用于Python 2的原始代码,而无需将float转换为int

str也是python内置的,因此将其用作变量是一种不好的做法。

此外,您希望Milkshakes的前半部分是Milks,而不是Milk

def first_half(s):
    #Parse float to int
    newword = int(len(s) / 2)
    return '{}'.format(s[:newword])

print(first_half('Milkshakes'))
#Milks

要像某些评论者所建议的那样,提出一个通用的解决方案,您可以使用整数除法//,该整数除法适用于Python 2Python 3

def first_half(s):
    #Integer division
    newword = len(s) // 2
    return '{}'.format(s[:newword])

print(first_half('Milkshakes'))
相关问题