Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove hyphens from a list of strings [duplicate]

Tags:

python

['0-0-0', '1-10-20', '3-10-15', '2-30-20', '1-0-5', '1-10-6', '3-10-30', '3-10-4']

How can I remove all the hyphens between the numbers?

like image 683
Hodgson Xue Avatar asked Dec 04 '16 01:12

Hodgson Xue


People also ask

How do you remove hyphens from a string?

Use the String. replace() method to remove all hyphens from a string, e.g. const hyphensRemoved = str. replace(/-/g, ''); . The replace() method will remove all hyphens from the string by replacing them with empty strings.

How do I remove dashes from a string in Python?

You can just iterate through with a for loop and replace each instance of a hyphen with a blank. This code should give you a newlist without the hyphens.

How do you remove an apostrophe in Python?

We can use the replace() function to remove apostrophes from string variables. To remove an apostrophe from a string, you can use replace() and pass an empty string as the replacement value as shown below. string_with_apostrophe = "I'm looking for the dog's collar." string_without_apostrophe = string_with_apostrophe.


Video Answer


2 Answers

You can just iterate through with a for loop and replace each instance of a hyphen with a blank.

hyphenlist = ['0-0-0', '1-10-20', '3-10-15', '2-30-20', '1-0-5', '1-10-6', '3-10-30', '3-10-4']
newlist = []

for x in hyphenlist:
    newlist.append(x.replace('-', ''))

This code should give you a newlist without the hyphens.

like image 76
SamOh Avatar answered Sep 28 '22 18:09

SamOh


Or as a list comprehension:

>>>l=['0-0-0', '1-10-20', '3-10-15', '2-30-20', '1-0-5', '1-10-6', '3-10-30', '3-10-4']
>>>[i.replace('-','') for i in l] 
['000', '11020', '31015', '23020', '105', '1106', '31030', '3104']
like image 40
LMc Avatar answered Sep 28 '22 19:09

LMc