2
\$\begingroup\$

Link To Question

Given a string, return a version without the first and last char, so "Hello" yields "ell". The string length will be at least 2.

without_end('Hello') → 'ell'

without_end('java') → 'av'

without_end('coding') → 'odin'

This is the code I wrote as a solution to this problem. I feel that this simple of a problem can be written in one line, but I can baffled as to how I can do so; after many attempts. Any and all feedback is appreciated and considered so I can further improve my python practices.

def without_end(str):

  if len(str) <= 2:
    return ""

  no_start = str[1:]
  no_end = no_start[:len(no_start) - 1]

  return no_end
\$\endgroup\$
5
\$\begingroup\$

You were right on track with

no_start = str[1:]
no_end = no_start[:len(no_start) - 1]

In a first step, they can be combined:

return str_[1:len(str_)-1]

Note: I changed str to str_ because str is actually a datatype in Python.

The next thing to know about slicing, is that you can use negative indices to index from the back without specifically using the length of the string like so:

return str_[1:-1]

And since this also works for strings with a length equal to two, you can also get rid of the earlier check.

So your are now down to basically:

def without_start_end(input_):
    return input_[1:-1]

Again take note: input_ also has the trailing _, since, you guessed it, input is already taken.


A non-directly code relate side-note: the official Style Guide for Python Code (aka PEP8) recommends to use 4 spaces per indentation level, and most people seem to follow that recommendation. There are however exceptions, e.g. Google's TensorFlow framework uses 2 spaces per indentation level (see their style guide), although Google's own "general purpose" style guide for Python code sticks with 4 spaces.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.