Remove First And Last Character From A String (Python vs Javascript)

Ahmed Radwan's photo
Ahmed Radwan
·Sep 3, 2022·

7 min read

Remove First And Last Character From A String (Python vs Javascript)

Photo by Sincerely Media on Unsplash

Subscribe to my newsletter and never miss my upcoming articles

Play this article

Table of contents

How python treats strings

This section is all about python and string manipulation. We want to remove the first and last character of string using the indexes. We will take a look with sample string to target the index we want to show or remove this specific character, whether it is the first character of string or it’s the last character.

Let’s take a look in this example with this original string “Nerd Level Tech”. By the way the string is always defined between double or single quotes, and the start of the string is always at index 0. Now with this in mind and with this entire string “Nerd Level Tech” we will have all our followed examples.

string = “Nerd Level Tech“';

Python with the positive indexes number: Python will make with each character in the string a corresponding index. Such as in the translation table below, first we will look at the positive indexes.

String Character Value String Character Index

  • N [0]
  • e [1]
  • r [2]
  • d [3]
  • Space [4]
  • L [5]
  • e [6]
  • v [7]
  • e [8]
  • l [9]
  • Space [10]
  • T [11]
  • e [12]
  • c [13]
  • h [14]

In the given string Python will give us the index position when we use this operator [], we should pass the index in the square brackets. It will return the specified character at that place. An index can be given either as positive or negative numbers that indicates where to look from the start or the end of a string (left to right or right to left).

print("Character: ", string[1]) # Output: Character: N

Python with the negative indexes number:

Now let’s take a look of how python is dealing with negative indexing for the same string.

String Character Value String Character Index

  • N [-15]
  • e [-14]
  • r [-13]
  • d [-12]
  • Space [-11]
  • L [-10]
  • e [-9]
  • v [-8]
  • e [-7]
  • l [-6]
  • Space [-5]
  • T [-4]
  • e [-3]
  • c [-2]
  • h [-1]
print("Character: ", string[-15]) # Output: Character: N

Inline removing the first and last character examples with the operator [] and indexes:

With the help of the operator in python we can use the start position which is before the “:” and the end position after the “:”

e.g.(start position here : end position here)

# Removing the last character in the whole string
string = str[:-1]  # Output: Nerd Level Tec
# Removing the first and last character in the whole string
string = string[1:-1] # Output: erd Level Tec

How javascript treats strings? Showing the positive indexes and negative indexes below. Javascript can also deal with a string almost the same way python does. I’m saying almost because some changes need to be done when dealing with negative indexes. There is always different ways and different techniques in programming. In my approach we will use the property length to reach out to the target character (new character) using the negative indexes. But first let’s take a look on the positive indexes.

Javascript with the positive indexes numbers:

String Character Value String Character Index

  • N [0]
  • e [1]
  • r [2]
  • d [3]
  • Space [4]
  • L [5]
  • e [6]
  • v [7]
  • e [8]
  • l [9]
  • Space [10]
  • T [11]
  • e [12]
  • c [13]
  • h [14]

Here we will use the property length to subtract from the string length to reach out to the targeted index. The length of the string in this example is 15 so 15 – 15 = 0 which is the first character in the string in this case is “N”.

Javascript with the negative indexes numbers:

String Character Value String Character Index

  • N [string.length -15]
  • e [string.length -14]
  • r [string.length -13]
  • d [string.length -12]
  • Space [string.length -11]
  • L [string.length -10]
  • e [string.length -9]
  • v [string.length -8]
  • e [string.length -7]
  • l [string.length -6]
  • Space [string.length -5]
  • T [string.length -4]
  • e [string.length -3]
  • c [string.length -2]
  • h [string.length -1]

Only two methods left before we learn our algorithm ( len() and slice() )

The method #1 for python is len()

The len() function counts the length of a string or any other objects. It returns the number of characters it contains, which is helpful for things like calculations.

myExample = "Nerd Level Tech"
x = len(myExample)
# -----------------------------
# Output:
# now x has the value of 15

I know what you going to say now: isn’t it like the property length in javascript. If you said that, you’re absolutely correct. Except this is a function and the javascript length is a property, we will take a look later on in future posts what the differences are between properties and functions .

The method #2 for javascript is slice()

The method has two parameters defining the first position in the first argument (first parameter) and the end position in the second argument (second parameter). Please note that the start / end position is not included when you want it to be shown. You need to increase the second parameter by one if you want to show the end character.

This method takes the values as positions in a string, then it will extract this part from the string in a new string.

let myExample = "Nerd Level Tech"
// note that the word "Level" start at 5 and end at 9, but by increasing 1 i included the "l"
// That's when i said above that the "increase the second parameter by one if you want to show the end"
let x = myExample.slice(5, 10)
// -----------------------------
// Output:
// The x have the value of "Level"

Now we’re ready to write our algorithm that contains how to remove the first and the last character of each word from a sentence.

Removing the first character and the last character from a string for each word

After we learnt how python and javascript deal with string from the above output, we should by now be more comfortable reaching out to a particular character in a string using the index number.

How do we remove the first and last character in each word?

The trick is easy once you know how to separate each word. We can treat the rest of the process as the same from the above examples.

In the example below we will take a look at how to do it. As I said the trick is simple, luckily we have a method that can separate the words based on a condition. This method is called split() and it’s called the same in both languages javascript and python.

All we need to do now is passing the string to the method split() with the space condition like that:

#Split the string based on the space
    arrForStr = str.split(" ");
// Split the string based on the space
  arrForStr = str.split(" ");

We did learn how to remove the first and the last characters of a string from the above code.

We now want to remove the first and last letter from a word in a string without using a regular expression. All of that and more in the following code.

# Python3 algorithm to removing first letter of each word and the last letter for same word

def RemoveFirstLastChar(str) :

    # Split the string on each of the spaces
    arrForStr = str.split(" ");

    # New string to store the new string
    resultStr = "";

    # This loop to remove the first and last character for each word
    for a in arrForStr :
        resultStr += a[1:len(a) - 1] + " ";

    return resultStr;

# Driver code
if __name__ == "__main__" :

  str = "Nerd Level Tech";

print(str);
print(RemoveFirstLastChar(str));

# Output
# -------------------
# Nerd Level Tech
# er eve ec
// Javascript algorithm to removing first letter of each word and the last letter for same word

function removeFirstLastChar(str) {
// Split the string on each of the spaces
  arrForStr = str.split(" ");

// New string to store the new string
  resultStr = "";

// Loop to remove the first and last character
for (a of arrForStr){
    resultStr += a.slice(1,-1) + " ";
  }
  return resultStr;
}

let str = "Nerd Level Tech"
console.log(str)
console.log(removeFirstLastChar(str))

// Output
// -------------------
// Nerd Level Tech
// er eve ec

Did you find this article valuable?

Support Ahmed Radwan by becoming a sponsor. Any amount is appreciated!

Learn more about Hashnode Sponsors
 
Share this