Last modified: Apr 05, 2023 By Alexander Williams

5 Methods to Remove Hyphens From String in Python

Method 1: Using string.replace()

# Define the string with hyphens
my_string = "hello-world-python"

# Use string.replace() to remove hyphens
new_string = my_string.replace('-', '')

# Print the new string
print(new_string)

Output:

helloworldpython

Method 2: Using regular expressions (Regex)

import re

# Define the string with hyphens
my_string = "hello-world-python"

# Use regular expressions to remove hyphens
new_string = re.sub('-', '', my_string)

# Print the new string
print(new_string)

Output:

helloworldpython

Method 3: Using str.translate()

# Define the string with hyphens
my_string = "hello-world-python"

# Define the translation table
translation_table = str.maketrans('-', '')

# Use str.translate() to remove hyphens
new_string = my_string.translate(translation_table)

# Print the new string
print(new_string)

Output:

helloworldpython

Method 4: Using list comprehension

# Define the string with hyphens
my_string = "hello-world-python"

# Use list comprehension to remove hyphens
new_string = ''.join([i for i in my_string if i != '-'])

# Print the new string
print(new_string)

Output:

helloworldpython

Method 5: Using list Pandas

import pandas as pd

# Create a DataFrame with a column containing strings with hyphens
df = pd.DataFrame({'String_Column': ['hello-world', 'python-is-great', 'data-science']})

# Use str.replace() to remove hyphens from the string column
df['String_Column'] = df['String_Column'].str.replace('-', '')

# Output the updated DataFrame
print(df)

Output:

    String_Column
0       helloworld
1     pythonisgreat
2      datascience