Home > Back-end >  User Input Slice String
User Input Slice String

Time:01-17

stringinput = (str(input("Enter a word to start: ")))
removeinput = (str(input("How many character's do you want to remove?")))
if (str)(removeinput) > (str)(stringinput):
    print("Cannot remove more chars than there are chars, try again")
else:
    removed = stringinput[-1,-removeinput,1]
    print((str)(removed))

Traceback (most recent call last):
  File "C:\Users\x\PycharmProjects\pythonProject\Pynative Beginner Tasks.py", line 110, in <module>
    removed = stringinput[-1,-removeinput,1]
TypeError: bad operand type for unary -: 'str'

I am doing an exercise to create an input that slices a string. I understand that removeinput needs to be converted to a string to be part of the slice but I don't know how to convert it in the else statement.

I also need it to be a string to make a comparison incase the user inputs a number greater than the amount of chars in stringinput

CodePudding user response:

It looks like you might be trying to take a slice from anywhere in the string, in which case you would need to get an input for the starting index and an ending index. In the example below I wrote it to remove the number of characters from the end of the string so if you input "hello" and "2" you are left with "hel". This behavior could be modified using the tutorial I have attached below.

Here's a modified version of your code with comments to explain the changes:

stringinput = input("Enter a word to start: ")
removeinput = int(input("How many character's do you want to remove? ")) // the int() function converts the input (a string) into an integer
if removeinput > len(stringinput):
    print("Cannot remove more chars than there are chars, try again")
else:
    removed = stringinput[:-removeinput] // remove the last characters based on the input
    print(removed)

In your code you use (str)(removeinput) and (str)(stringinput). It looks like you are trying to cast the variables as strings, but this is not necessary as both of them are already strings by default. In the modified code I converted the input into an integer using int(). This is because your input is not an integer, it is the string version of the integer. By using int(), we are comparing the integer version of the input.

To address the error that you were getting, the syntax that you are using is not correct. Strings are indexed using colons in Python, not commas. Here is a tutorial that might help you: https://www.digitalocean.com/community/tutorials/how-to-index-and-slice-strings-in-python-3

I hope this helps!

  • Related