54m
54m

Reputation: 767

How to remove whitespace in a list

I can't remove my whitespace in my list.

invoer = "5-9-7-1-7-8-3-2-4-8-7-9"
cijferlijst = []

for cijfer in invoer:
    cijferlijst.append(cijfer.strip('-'))

I tried the following but it doesn't work. I already made a list from my string and seperated everything but the "-" is now a "".

filter(lambda x: x.strip(), cijferlijst)
filter(str.strip, cijferlijst)
filter(None, cijferlijst)
abc = [x.replace(' ', '') for x in cijferlijst]

Upvotes: 0

Views: 9899

Answers (3)

coder
coder

Reputation: 12972

Try that:

>>> ''.join(invoer.split('-'))
'597178324879'

Upvotes: 4

A. Dickey
A. Dickey

Reputation: 141

This looks a lot like the following question: Python: Removing spaces from list objects

The answer being to use strip instead of replace. Have you tried

abc = x.strip(' ') for x in x

Upvotes: 1

Moinuddin Quadri
Moinuddin Quadri

Reputation: 48077

If you want the numbers in string without -, use .replace() as:

>>> string_list = "5-9-7-1-7-8-3-2-4-8-7-9"
>>> string_list.replace('-', '')
'597178324879'

If you want the numbers as list of numbers, use .split():

>>> string_list.split('-')
['5', '9', '7', '1', '7', '8', '3', '2', '4', '8', '7', '9']

Upvotes: 2

Related Questions