如何找出变量中有多少行

how to find out how many lines are in a variable

我正在做一个 Telegram 机器人,我想在内联键盘中打印字符串。我有一个可以更改的变量 text,我想检查变量中有多少行(字符串)可以使用它 0<name<2 并进行限制。怎么做到的?

我可以用 len() 实现,但它告诉我 list index out range

text="head,hand,..."

selectKeyboard = telebot.types.InlineKeyboardMarkup( row_width=1)

if 0<name<2:
    for i in range(len(text)):
        one=types.InlineKeyboardButton(text=str(text[0]['name']),callback_data="first")

    selectKeyboard.add(one)

if 0<name<3:
    for i in range(len(text)):
        one=types.InlineKeyboardButton(text=str(text[0]['name'])+"  ",callback_data="first")
        two=types.InlineKeyboardButton(text=str(text[1]['name'])+"  ",callback_data="second")

    selectKeyboard.add(one,two)

if 0<name<4:
    for i in range(len(text)):
        one=types.InlineKeyboardButton(text=str(text[0]['name'])+"  ",callback_data="first")
        two=types.InlineKeyboardButton(text=str(text[1]['name'])+"  ",callback_data="second")
        three = types.InlineKeyboardButton(text=str(text[2]['name']) + "  " ,callback_data="three")

    selectKeyboard.add(one,two,three)

if 0<name<5:
    for i in range(len(text)):
        one=types.InlineKeyboardButton(text=str(text[0]['name'])+"  ",callback_data="first")
        two=types.InlineKeyboardButton(text=str(text[1]['name'])+"  "+,callback_data="second")
        three = types.InlineKeyboardButton(text=str(text[2]['name']) + "  " ,callback_data="three")
        four = types.InlineKeyboardButton(text=str(text[3]['name']) + "  " , callback_data="four")

    selectKeyboard.add(one,two,three,four)

if 0<name<6:
    for i in range(len(text)):
        one=types.InlineKeyboardButton(text=str(text[0]['name'])+"  ",callback_data="first")
        two=types.InlineKeyboardButton(text=str(text[1]['name'])+"  ",callback_data="second")
        three = types.InlineKeyboardButton(
            text=str(text[2]['name']) + "  " ,
            callback_data="three")
        four = types.InlineKeyboardButton(
            text=str(text[3]['name']) + "  " ,
            callback_data="four")
        five=types.InlineKeyboardButton(
            text=str(text[4]['name']) + "  " ,
            callback_data="five")

    selectKeyboard.add(one, two, three, four,five)

下面这段代码并没有按照你的想象去做,实际上它只是 return False,因为 name 是一个 string 而你'重新将它与整数进行比较:

0 < name < 2

相反,您应该测试变量的数量,如下所示:

text = "head,hand,..."
num_vars = len(text.split(','))

if 0 < num_vars < 2:
    # same for all the other comparisons