-1

这是我的代码:

str1 = "Hello How are you dude?"
print("\nInitial String :" + str1)
n = int(input("Enter index number to remove character from above string :"))


if n <= len(str1):
    first_part = str1[:n]
    second_part = str1[n+1:]
    final_string = first_part + second_part
    print("Result String :", final_string)
else:
    print("Your Entered Number is out of the range..!!")

他是我的输出:

Initial String :Hello How are you dude?
Enter index number to remove character from above string :23
Result String : Hello How are you dude?

当我输入一个字符串的总长度 + 1 时,它给我的输出与我的原始字符串相同。您也可以在我提到输出的代码中看到。它将如何发生?谁能解释一下?

4

2 回答 2

1

由于str是 0 索引,您的条件应该是

if n < len(str1): # and not <=

给予

if n < len(str1):
    final_string = str1[:n] + str1[n + 1:]
    print(f"Removed char '{str1[n]}'")       # Useful for debug purpose
    print("Result String :", final_string)
else:
    print("Your Entered Number is out of the range..!!")
于 2021-04-13T10:30:53.270 回答
0

在您的if 条件中,您提到如果n<=len(str)您将输入作为 23 并且后面的行将使得 first_part 的值等于从 0 到 22 索引的原始字符串,该字符串本身的长度为 23,则 if which 变为 True ,与原始字符串相同细绳。

换句话说,您试图从长度为 23 的字符串中删除第 24 个字符(n=23),这就是您获得完整字符串的原因。

于 2021-04-13T10:38:24.610 回答