Remove the hyphens from a list of strings in Python

avatar

Borislav Hadzhiev

Last updated: Aug 14, 2022

banner

Photo from Unsplash

Remove the hyphens from a list of strings in Python #

To remove the hyphens from a list of strings:

  1. Use a list comprehension to iterate over the list.
  2. Use the str.replace() method to remove the hyphens from each string.
  3. The strings in the new list won't contain any hyphens.
main.py
my_list = [ '1-2-3', '4-5-6', '7-8-9', '1-2-3' ] result = [item.replace('-', '') for item in my_list] print(result) # 👉️ ['123', '456', '789', '123']

We used a list comprehension to iterate over the list of strings.

List comprehensions are used to perform some operation for every element or select a subset of elements that meet a condition.

On each iteration, we use the str.replace() method to remove the hyphens from the current string and return the result.

main.py
print('1-2-3'.replace('-', '')) # 👉️ '123' print('4-5-6'.replace('-', '')) # 👉️ '456'

The str.replace method returns a copy of the string with all occurrences of a substring replaced by the provided replacement.

The method takes the following parameters:

NameDescription
oldThe substring we want to replace in the string
newThe replacement for each occurrence of old
countOnly the first count occurrences are replaced (optional)

The method doesn't change the original string. Strings are immutable in Python.

We remove all hyphens from each string in the list by replacing them with empty strings.

Alternatively, you can use a for loop.

To remove the hyphens from a list of strings:

  1. Declare a new variable and set it to an empty list.
  2. Use a for loop to iterate over the list of strings.
  3. Use the replace() method to remove the hyphens from each string.
  4. Append the result to the new list.
main.py
my_list = [ '1-2-3', '4-5-6', '7-8-9', '1-2-3' ] result = [] for item in my_list: result.append(item.replace('-', '')) print(result) # 👉️ ['123', '456', '789', '123']

The result variable will store the strings that don't contain any hyphens.

We used a for loop to iterate over the list of strings.

On each iteration, we use the str.replace() method to remove the hyphens from the current string and append the new string to the end of the result list.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.