0

Hi I am new to Python and was trying to achieve the function of removing the empty spaces in both ends using.

trim_1() works perfect , but I got this error when using the trim_2():

IndexError: string index out of range 

So s[:1] and s[0] are not the same thing? Why s[:1] works and s[0] does not? Anyone could shed some light on this?

def trim_1(s) :
    while s[:1]  == ' ':
        s= s[1:]
    while s[-1:] == ' ':
        s= s[:-1]
    return s


def trim_2(s) :
    while s[0] == ' ':
        s= s[1:]
    while s[-1] == ' ':
        s= s[:-1]
    return s
blhsing
  • 91,368
  • 6
  • 71
  • 106
Pan Xin
  • 13
  • 2
  • 1
    No they are not the same thing, `s[0]` is the first character, `s[:-1]` is the whole string. On the other hand, `s[0] == s[-len(s)]` and `s[-1] == s[len(s)-1]`. What you are trying to achieve can be done using `s.strip()`. – cglacet Mar 19 '19 at 18:22

3 Answers3

1

This is because Python is tolerant towards out-of-bound indices for slices, while intolerant towards out-of-bound indices for lists/strings themselves, as demonstrated below:

>>> ''[:1] # works even though the string does not have an index 0
''
>>> ''[0]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: string index out of range
blhsing
  • 91,368
  • 6
  • 71
  • 106
1

If you are asking for a specific index then you are telling the computer that your code requires the value to proceed. Therefore, there must be an element at the specified index or you will see the error. When using this method it is common practice to check first, for example:

value = None
if len(s) > 0:
    value = s[0]  # if index 0 doesn't exist, and error will be thrown

If you are asking for an open ended "slice" like that then you are telling the computer that you want all elements in a specified range. You the programmer will need to handle the possible outcomes: no elements exist, 1 element exists, more than one element exists.

values = s[:0]  # returns variable number of elements
if len(values) == 0:
    ...
elif len(values) > 0:
    ...

Both methods have their uses. Remember that you the programmer are in control. These are both just tools you can use to solve your issue. With each option comes different edge cases that you have to handle. Keep in mind that there are one or two appropriate data structure(s) for every scenario. If you are using an inappropriate one, like putting object properties into an array instead of using a class, you will find your code looking cumbersome and ugly. Just something to keep in mind. Stuff like this just makes sense as you get more experienced. Hope that helps!

Timothy Jannace
  • 1,401
  • 12
  • 18
0

Have you tried -

sentence = ' hello  apple '
sentence.strip()
Regressor
  • 1,843
  • 4
  • 27
  • 67