Remove the First Character From the String in Python

Muhammad Waiz Khan Jan 30, 2023 Jan 28, 2021
  1. Remove the First Character From the String in Python Using the Slicing
  2. Remove the First Character From the String in Python Using the str.lstrip() Method
  3. Remove the First Character From the String in Python Using regex Method
Remove the First Character From the String in Python

This tutorial will discuss how we can remove the first character from the string in Python using multiple methods. Note that the string in Python is immutable, which means we can not make changes in a string in Python. Therefore, in order to remove a character from the string, we will make a new string that will not have the first character we wanted to remove.

Remove the First Character From the String in Python Using the Slicing

If we want to remove the first or some specific character from the string, we can remove that character using the slicing - str[1:]. str[1:] gets the whole string except the first character.

For example, we need to remove the first character from the string hhello.

string = "hhello"
new_string = string[1:]
print(new_string)

Output:

hello

Remove the First Character From the String in Python Using the str.lstrip() Method

The str.lstrip() method takes one or more characters as input, removes them from the start of the string, and returns a new string with removed characters. But be aware that the str.lstrip() method will remove the character(s) if they occur at the start of the string one or multiple times.

The example code below demonstrates how we can use the str.lstrip() method to remove character(s) from the start of the string.

string = "Hhello world"
new_string = string.lstrip("H")
print(new_string)

string = "HHHHhello world"
new_string = string.lstrip("H")
print(new_string)

Output:

hello world
hello world

Remove the First Character From the String in Python Using regex Method

The re.sub() method of the re library can also be used to remove the first character from the string. The re.sub() method replaces all the characters matches the given regular expression pattern argument with the second argument.

Example code:

import re

string = "Hhello world"
new_string = re.sub(r'.', '', string, count = 1)
print(new_string)

In the above code, count = 1 specifies the re.sub method only replaces the given pattern, at max, once.

Output:

hello world

Related Article - Python String