Skip to Content

Python – Remove Leading Underscores From String

In this tutorial, we will look at how to remove leading underscores from a string in Python with the help of some examples.

remove leading underscores from a string

You can use the string lstrip() function to remove leading underscores from a string in Python. The lstrip() function is used to remove characters from the start of the string and by default removes leading whitespace characters.

To remove leading underscores with the lstrip() function, pass the underscore character, '_' as an argument. Let’s look at an example.

# create a string
s = "_not a doctor"
# remove leading underscores
s.lstrip('_')

Output:

'not a doctor'

The resulting string doesn’t have any underscore characters in the beginning.

Highlighted programs for you

Flatiron School

Flatiron School

Data Science Bootcamp
Product Design UX/UI Bootcamp

University of Maryland Global Campus

University of Maryland Global Campus

Cloud Computing Systems Master's
Digital Forensics & Cyber Investigation Master's

Creighton University

Creighton University

Health Informatics Master's

Note that the lstrip() function only removes characters from the start of the string. So, for example, if underscores are present in the middle, or at the end of a string, they will not be removed.

# create a string
s = "_not_a_doctor_"
# remove leading underscores
s.lstrip('_')

Output:

'not_a_doctor_'

You can see that only the leading underscores were removed from the string.

Similarly, you can use the string lstrip() function to remove any character from the beginning of the string.

To remove all the occurrences of the underscore character irrespective of where it occurs in the string, you can use the string replace() function. For example –

# create a string
s = "_not_a_doctor_"
# remove all underscores
s.replace('_', '')

Output:

'notadoctor'

The resulting string does not have any underscore characters. Here we use the string replace() function to replace all the occurrences of the underscore with an empty string. You can choose any character as a replacement to the underscore character depending upon your use case.


You might also be interested in –


Subscribe to our newsletter for more informative guides and tutorials.
We do not spam and you can opt out any time.


Author

  • Piyush Raj

    Piyush is a data professional passionate about using data to understand things better and make informed decisions. He has experience working as a Data Scientist in the consulting domain and holds an engineering degree from IIT Roorkee. His hobbies include watching cricket, reading, and working on side projects.