The most efficient and Pythonic way to remove the first character from a string is by starting the slice from index 1 and leaving the end index empty to include all remaining characters.
my_string = "Apple" print(my_string) # Output: Apple # Removing the first character new_string = my_string[1:] print(new_string) # Output: pple
In this code, my_string[1:] means we are slicing the string from index 1 and going till the end of the string. The 0th index (H) is left out, which effectively strips the first character.
The time complexity is O(n), where n is the string length (creates a new string).
Alternate ways
Using str.removeprefix() (Python 3.9+)
Python 3.9 introduces the str.removeprefix() method that removes the specific prefix if it exists, not just any first character.
What we need to do is pass the first character of the string to the str.removeprefix() method, and it returns a new string with that character stripped.
text = "Apple" result = text.removeprefix(text[0]) print(result) # Output: pple
If the character you are trying to delete does not exist, it won’t throw any error; instead, it returns an unchanged string.
Using lstrip()
The lstrip() method removes leading characters if they match a specified set (not just one character).
my_string = "Apple" print(my_string) # Output: Apple new_string = my_string.lstrip(my_string[0]) print(new_string) # Output: pple
The lstrip() method accepts an argument to strip from a string, and in our case, it is the first character denoted by my_string[0].
When using lstrip(), keep in mind that if your input string is “AAAple” and you want to remove the character “A”, it will remove all three “A”.
So, in this case, it does not remove the first character; it removes the first three characters. So, use it with caution.
triple_string = "AAApple" print(triple_string) # Output: AAApple stripped_string = triple_string.lstrip(triple_string[0]) print(stripped_string) # Output: pple
As you can see from the output, all three A’s are gone,
Using re.sub()
The re.sub() function performs a search and replace operation on strings. In this case, the regular expression ‘^.’ is used, where the caret ^ denotes the start of the string, and the dot (.) matches any single character.
It is useful when you need more complex pattern matching.
import re my_string = "Apple" print(my_string) # Output: Apple # Regular expression '^.' matches the first character of the string new_string = re.sub('^.', '', my_string) print(new_string) # Output: pple
That’s all!