0
def missing_char(str,n):
    front = str[:n]
    back = str[n+1:]
    return front + back

I don't really understand what is being said when back is defined, and furthermore I don't understand how this actually takes out the letter you specify when you enter a word into the function with the "return front + back" part.

Thanks everyone for the help, you all made me understand it better :).

Djj
  • 3
  • 3

4 Answers4

7

str[:n] copies the string from the start up to, but not including, the n:th character. str[n+1:] copies the string from the (n+1):th character to the end.

Adding both these strings will result in all the characters of the original string, except for the n:th character.

str[:n] is a shorthand for str[0:n], and str[n:] is a shorthand for str[n:len(str)].

bos
  • 6,437
  • 3
  • 30
  • 46
  • 1
    If you found the answer useful, don't forget to click the accept button. And, welcome to Stack Overflow. – bos Mar 27 '12 at 07:42
  • Another way to put it: it's a way to do `del sequence[n:n+1]` on an immutable sequence like a string or a tuple. – agf Mar 27 '12 at 07:59
  • 1
    @Djj: No, you didn't. There shoul be a green ✓ on the left. Click on the outlined ✓ of your favourite answer. – glglgl Mar 27 '12 at 08:14
3
front = str[:n] 
# get prefix of str with n characters
# for str = "hello" and n=2 front = "he"

back = str[n+1:] 
# get suffix of the string starting from n+1th character
# for str = "hello" and n=2 back = "lo"

front + back 
# concatenation of front + back, which is "he" + "lo" = "helo"
# So this small method basically removes the nth character
dbr
  • 165,801
  • 69
  • 278
  • 343
mdakin
  • 1,310
  • 11
  • 17
2

front is calculated as all letters in str up to position n, then back is calculated as all letters in str from position n+1 - ie skipping the letter at n itself. Then front + back simply concatenates the two fragments back together and returns the resulting string.

Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895
0

Let's look at "Hello, World!" and take out character 5 (who needs punctuation anyway).

When you call missing_char, you get the following steps:

  1. front is set to "Hello" (the characters from zero to n)
  2. back is set to " World!" (the characters from n+1 to the end)
  3. The concatenation of front and back is returned, basically putting back on the end of front, resulting in our final answer of "Hello World!".

You may want to look at splicing in more detail, something like this answer is really good for that. It is a very powerful feature once understand.

Community
  • 1
  • 1
Matt
  • 7,100
  • 3
  • 28
  • 58