Remove the First Character From the String in Python

  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

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
Contribute
DelftStack is a collective effort contributed by software geeks like you. If you like the article and would like to contribute to DelftStack by writing paid articles, you can check the write for us page.

Related Article - Python String

  • Split String Based on Multiple Delimiters in Python
  • Check a String Is Empty in a Pythonic Way