r/pythonhelp • u/[deleted] • Feb 19 '22
Python project of grade
It's pretty straightforward. Your goal is to create a function that removes the first and last characters of a string. You're given one parameter, the original string. The input will always be at least 2 characters.
def remove_char(s):
What do I have to do in this problem? Please I really need it.
0
Upvotes
1
Feb 21 '22
def shorten_string(string: str) -> str:
return string[1:-1]This doesn't care about the length of the string provided in the call - will not fail even if zero length string is passed - but problem statement says you are guaranteed to be provided with at least min 2-character length string.
1
u/MT1961 Feb 19 '22
Well, if the string is two characters, it is pretty simple. You return an empty string ""
In all other cases, you want the substring from the 2nd character to the 2nd to last character. So, essentially, you have a string s.
s[1:-1]
because 1 is the 2nd character. -1 is the end of the string -1.
For example, suppose we have:
s = "123"
if you print(s[1:-1])
you will get
2
If your string were something longer, say, '12345678'
Then s[1:-1] gives you
'234567'
which is what you want.
So, basically, wrap what you just learned in a function and return the result, and you are done.