Remove all the underscores from a string in Python

In this article, we will learn about how to remove underscores from a string in Python.

Introduction:

In Python, underscore is a all-round symbol. Underscores are used to declare variable or function in code and it is also used to store the value of expression in the interpreter.

There are two types of underscores in Python. They are:

  • Single underscore (_)
  • Double underscore (__)

Single underscore:

Single underscore is used to indicate that a variable is temporary and inconsequential. It is also used to store the result of last expression.

EX:

for _ in range(32):
  print('Good, Morning.')

In the above loop we don’t need to access the running index and we can use “_” to indicate that it is just a temporary value.

Double underscore:

Double underscore is used for the mangling of the game. They are used to avoid naming conflicts of classes in Python.

Ex:

class Example:
    def __init__(self):
        self.__personal_attribute = "This is personal"
    def get_personal_attribute(self):
        return self.__personal_attribute
example = Example()
print(example.get_personal_attribute())
print(example._Example__personal_attribute)

In the above example, __personal_attribute  gets name mangled to _Example__personal_attribute to avoid naming conflict.

Uses of removing of underscores from a string in Python:

  • Underscore is removed to make text more readable and to understand easily.
  • The URls or slugs will be more cleaned and easily understandable.
  • We can make sure equal string formatting while Data cleaning.

Methods for removing underscores from a string in Python:

1.Using ‘str_replace()’:

real_string = "jack_123"
no_underscores = real_string.replace("_", "")
print(no_underscores)

output:

jack123

2.Using isalpha():

string = 'jack_123' 
last_string = ' ' 
for i in string: 
    if i.isalpha(): 
        last_string += i 
print(last_string) 

output:

jack

3. using list comprehension:

string = 'jack_123' 
print(''.join([i for i in string if i.isalpha()])) 

output:

jack

By using above methods we can easily remove underscores from a string in Python.

Leave a Reply

Your email address will not be published. Required fields are marked *