0

I have this code at the moment.-

code = input("Please enter the code: ")
inst_1 = code.find("(")
inst_2 = code.rfind(")")

print(code[range(inst_1, inst_2)])

I'm trying to get it to print any parts of the input that are typed in between brackets. I've tried using range so that it can print out any input in between the index of the opening and closing brackets but that just returns an error as my inst_1 and inst_2 aren't integers.

  • 1
    Can you give us the exact error message? Because this code shouldn't complain about `inst_1` nor `inst_2`. And the syntax you may be looking for is `code[inst_1:inst_2]`. – deceze Aug 10 '23 at 09:27

2 Answers2

0

You're almost there, but instead of range there is the slicing syntax:

print(code[inst_1+1:inst_2])
Aemyl
  • 1,501
  • 1
  • 19
  • 34
0

You're on the right track using the find() method to locate the positions of the opening and closing brackets. However, the issue with your code is that you are trying to use the range function within the string slice notation which is incorrect. Instead, you should use slicing directly with the indices inst_1 and inst_2.

Here's a corrected version of your code:

    code = input("Please enter the code: ")
inst_1 = code.find("(")
inst_2 = code.rfind(")")

# The slice should start from inst_1+1 to skip the opening bracket and end at inst_2 to skip the closing bracket
print(code[inst_1+1:inst_2])