首页 > 解决方案 > 我收到此代码显示 TypeError: '>=' not supported between 'str' 和 'int' 实例

问题描述

下面的代码抛出一个 TypeError

string1 = input("STRING 1: ")
string2 = input("STRING 2: ")

string2 = []
string1 = []
print(string1)
print(string2)

which_string = int(input("select which String you want to del a CHARACTER from 1 or 2: "))

which_string = True

while True:   
    if which_string ==1:
        index = input("select index you want to del from: ")
    
        while index >= len(string1):
            index = int(input("Your selection was not in range - TRY AGAIN: "))
            string_list = list(string1)
            string_list.pop(index)
            string1 = "".join(string_list)
            #print(string1)


    elif which_string==2:
        index = input("select index you wan to del from: ")

        while index >= len(string2):
            index = int(input("Your selection was not in range - TRY AGAIN: "))
            string_list = list(string2)
            string_list.pop(index)
            string1 = "".join(string_list)
            break
    else:
        which_string = int(input("select which STRING you want to del a CHARACTER from 1 or 2: "))
print(string1)
print(string2)

我的目标是编写一个程序:

  1. 接受输入 2 个字符串
  2. 询问哪个字符串用户想要从 - string1 或 string2 中删除一个字符。
  3. 然后询问从哪个索引删除一个字符
  4. 然后打印出 2 个字符串

标签: python

解决方案


您没有指出此错误出现的位置,但似乎您正在尝试这样做index >= len(string1) and index >= len(string2),即使索引是来自输入的字符串并且 len() 是 int。

您需要注意,目前 index 仍然是一个字符串。您只是在 while 内将其转换为 int,但 while 无法启动,因为您无法执行 str >= int。

所以你应该这样做:index = int(input("select index you want to del from: ")) 而不是:index = input("select index you want to del from: ")


推荐阅读