Home > katas > Remove First and Last Character (8kyu) [Python]
Remove First and Last Character (8kyu) [Python]
Chek kata on Codewars
Description:
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. You don't have to worry with strings with less than two characters.
Solution 1.1
Let's start with a naive solution. Solving with loop
.
def remove_char(str):
newS = ''
for index in range(len(str)):
if (index != 0 and index != len(str) - 1):
newS += str[index]
return newS
Solution 1.2
We can make it a little bit cleaner by using not
def remove_char(str):
newS = ''
for index in range(len(str)):
if (not(index == 0 or index == len(str) - 1)):
newS += str[index]
return newS
Solution 2.1
A more efficient solution will be to use slice
method.
def remove_char(str):
return str[1: len(str) - 1]
Solution 2.2
We can make it a little bit shorter.
def remove_char(str): return str[1: - 1]
Solution 3.1
Not the most efficient solution. But we can convert a string to an array and use array methods.
def remove_char(str):
new_list = list(str)
new_list.pop()
new_list.pop(0)
return ''.join(new_list)
Solution 4.1
Also, we can use a regular expression here with the replace method.
import re
def remove_char(str): return re.sub('^.|.$', '', str)