2

I am looking forward to get rid of a space that is after each element in my list:

  list1 = ['Aena', 'Cellnex Telecom', 'Amadeus', 'Abertis']

in order to obtain the list like this:

  list1 = ['Aena','Cellnex Telecom','Amadeus','Abertis']

I have tried the following loop but returns the same initial list:

new_list = [stocks.replace(" ","") for stocks in list1]

and

new_list = [stocks.replace(", '",",'") for stocks in list1]

print(new_list)

Could anyone help me to obtain the desired list without the spaces?

2
  • 1
    I think you have to understand, that print(..) prints the representation of a list. With the list comprehension, you alter the elements themselves. Afaik you can't do much about how print prints the list itself. But you can write your own print method. Commented Jun 25, 2017 at 14:57
  • Thank you for the explanation, very clear Commented Jun 25, 2017 at 15:05

2 Answers 2

5

I think you have to understand, that print(..) prints the representation of a list (which is a comma separated list surrounded by square brackets).

With the list comprehension, you alter the elements themselves. As far as I know you can't do much about how print prints the list itself. But you can write your own print method.

We can do this by using a join on the repr(..) of the elements, and surround it by square brackets, like:

print('[{}]'.format(','.join(repr(x) for x in list1)))

This prints:

>>> print('[{}]'.format(','.join(repr(x) for x in list1)))
['Aena','Cellnex Telecom','Amadeus','Abertis']
Sign up to request clarification or add additional context in comments.

3 Comments

completely identical expressions. what are the odds 😂😂?
@Uriel: I just wanted to say the same :)
btw. great answers both!
4
>>> print('[{}]'.format(','.join(repr(x) for x in list1)))
['Aena','Cellnex Telecom','Amadeus','Abertis']

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.